douchiwan1503 2013-09-16 18:16
浏览 34
已采纳

在多维数组中查找索引

Basically I have this array:

array(
  [0] => array("id" => "0", "header" => "img1"),
  [1] => array("id" => "4", "header" => "img4")
  [2] => array("id" => "6", "header" => "img6")
)

If I have $id = "4", how can I extract the index [1] to obtain "header" value?

  • 写回答

3条回答 默认 最新

  • doutan5724 2013-09-16 18:22
    关注

    You will want to do a foreach loop for this. But honestly if you structured your array indexes better than you could just to a simple isset test and then grab the value once you verify it is there.

    The right way:

    $headers = array(0 => 'img1', 4 => 'img4', 6 => 'img6');
    
    if (isset($headers[$index])) {
      return $headers[$index];
    }
    

    Here is how to deal with it with your array (much more costly from a processing standpoint):

    $headers = array(
      0 => array("id" => "0", "header" => "img1"),
      1 => array("id" => "4", "header" => "img4"),
      2 => array("id" => "6", "header" => "img6")
    );
    
    foreach ($headers AS $value) {
      if ($value['id'] == $index) {
        return $value['header'];
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统