Welcome Guest, Not a member yet? Register   Sign In
Multidimensional array generate
#1

[eluser]karloff[/eluser]
Hi,

i'm trying to create a search feature which bring back results of how close you are to a particular place. my problem is that I need to add the info of each place into a multidimensional array, with the added field of the distance, so i can sort it....

this is my code so far but It keep generating php errors,

Is this possible or am i going about it the wrong way?



Code:
$item = $this->cfmmodel->get_all_places();
$postcode = $this->cfm_lib->clean_postcode($_POST['postcode']);
$long = $this->postcodemodel->getLong($postcode);
$lat = $this->postcodemodel->getLat($postcode);

$data['multi'] = Array(
                    foreach ($items as $item)
                    {
                    
                    array(
                   'id' => $item->id,
                   'name' => $item->name,
                   'distance' => $this->cfm_lib->getDistance($lat[0]->Lat, $long[0]->Long, $item->Lat, $item->Long),
                    ),

                }
                );
#2

[eluser]darkhouse[/eluser]
Why does it have to be multidimensional? What's wrong with doing this?

Code:
foreach ($items as &$item){
   $item['distance'] = $this->cfm_lib->getDistance($lat[0]->Lat, $long[0]->Long, $item->Lat, $item->Long);
}

Notice the & in front of $item in the foreach statement. This references each $item so it will affect the $items array. But now you just have one array with a distance value for each element.

Or, if you're using php4 still, you could do this:

Code:
for($i = 0; $i < count($items); $i++){
   $items[$i]['distance'] = $this->cfm_lib->getDistance($lat[0]->Lat, $long[0]->Long, $items[$i]->Lat, $items[$i]->Long);
}

Same thing, really. I just prefer the foreach method, it's cleaner.
#3

[eluser]karloff[/eluser]
hey man, this sounds ideal but i'm having trouble implementing it

Code:
Cannot use object of type stdClass as array in ......

why would that be??

ps. its php5 but thanks for the insight for the diff between php 4 and 5 Smile
#4

[eluser]darkhouse[/eluser]
Oh try this instead...

Code:
foreach ($items as &$item){
   $item->distance = $this->cfm_lib->getDistance($lat[0]->Lat, $long[0]->Long, $item->Lat, $item->Long);
}
#5

[eluser]karloff[/eluser]
got it sorted

Code:
$item->distance = $this->cfm_lib->getDistance($lat[0]->Lat, $long[0]->Long, $item->Lat, $item->Long);
}
#6

[eluser]karloff[/eluser]
ha ha, thanks for the reply, i just posted the exact same thing as you at the same time.... made me laugh...


cheers
#7

[eluser]darkhouse[/eluser]
Haha yeah, I just posted that. I shoulda caught that when I first posted.




Theme © iAndrew 2016 - Forum software by © MyBB