Tom
Tom

Reputation: 11

Getting Specific Data from Array of Objects

I have an array of Objects like this:

`array(1)
{ 
 ["networks"]=> array(20) 
  { 
   [0]=> object(stdClass)#2 (11) 
    { 
      ["name"]=> string(17) "Ghostlight Coffee" 
      ["id"]=> int(193086) 
      ["is_fcc"]=> bool(true) 
      ["latitude"]=> float(39.750251) 
      ["longitude"]=> float(-84.175353) 
      ["down_repeater"]=> int(0) 
      ["down_gateway"]=> int(0) 
      ["spare_nodes"]=> int(0) 
      ["new_nodes"]=> int(0) 
      ["node_count"]=> int(1) 
      ["latest_firmware_version"]=> string(10) "fw-ng-r589" 
  } 
   [1]=> object(stdClass)#3 (11) 
    { 
      ["name"]=> string(8) "toms new" 
      ["id"]=> int(188149) 
      ["is_fcc"]=> bool(true) 
      ["latitude"]=> float(39.803392) 
      ["longitude"]=> float(-84.210273) 
      ["down_repeater"]=> int(0) 
      ["down_gateway"]=> int(1) 
      ["spare_nodes"]=> int(0) 
      ["new_nodes"]=> int(0) 
      ["node_count"]=> int(1) 
      ["latest_firmware_version"]=> string(10) "fw-ng-r573"
}'

The array continues, but this should give you the idea. Basically I need to be able to search this array by "Name" and pull the associating "id" for use another function. Any ideas on how to do this? I don't want to use a loop, because this array will become several hundred objects long so I think that would take up too much time. I've tried array_search and I always get a false boolean. I'm kinda stuck.

Upvotes: 1

Views: 45

Answers (2)

fusion3k
fusion3k

Reputation: 11689

On PHP 7 you can use array_column to create an array with “name” values. Then with array_search you can retrieve appropriate key:

$names = array_column( $array['networks'], 'name' );
$key = array_search( 'toms new', $names );

if( $key !== False ) $id = $array['networks'][$key]->id;

On PHP < 7, transform array of objects in array of arrays, then you can use same method with converted array:

$array2 = json_decode( json_encode( $array ), True );
$names = array_column( $array2['networks'], 'name' );
$key = array_search( 'toms new', $names );

if( $key !== False ) $id = $array['networks'][$key]->id;

Upvotes: 1

iainn
iainn

Reputation: 17417

Unless you can index the data by name then a loop is the only way to go, I'm afraid. That's all array_search is going to be doing under the hood anyway. Unless the array is going to move way up into the thousands, the performance hit probably won't be noticeable anyway.

$search = 'Ghostlight Coffee';

foreach ($array['networks'] as $network)
{
    if ($network->name == $search)
    {
        $id = $network->id;
        break;
    }
}

Upvotes: 0

Related Questions