【问题标题】:Getting Specific Data from Array of Objects从对象数组中获取特定数据
【发布时间】:2016-04-26 14:34:23
【问题描述】:

我有一个这样的对象数组:

`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"
}'

数组继续,但这应该给你的想法。基本上我需要能够通过“名称”搜索这个数组并拉出关联的“id”以使用另一个函数。关于如何做到这一点的任何想法?我不想使用循环,因为这个数组会变成几百个对象,所以我认为这会占用太多时间。我试过array_search,但我总是得到一个错误的布尔值。我有点卡住了。

【问题讨论】:

    标签: php arrays object


    【解决方案1】:

    PHP 7 上,您可以使用 array_column 创建具有“名称”值的数组。然后使用array_search,您可以检索适当的密钥:

    $names = array_column( $array['networks'], 'name' );
    $key = array_search( 'toms new', $names );
    
    if( $key !== False ) $id = $array['networks'][$key]->id;
    

    PHP 中,将对象数组转换为数组数组,然后您可以使用与转换后的数组相同的方法:

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

    【讨论】:

      【解决方案2】:

      除非您可以按名称索引数据,否则循环是唯一的方法,恐怕。无论如何,这就是 array_search 要做的所有事情。除非该阵列将向上移动到数千个,否则性能影响可能不会很明显。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-05
        • 2015-06-07
        • 1970-01-01
        • 2018-02-14
        相关资源
        最近更新 更多