1

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.

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.