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

在多维数组中查找索引

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
    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'];
      }
    }
    
    点赞 评论
  • dpw5865
    dpw5865 2013-09-16 18:19
    foreach ($array as $key => $value) {
        if ($value['id'] == '4') {
            echo $value['header'];
            break;
        }
    }
    

    It will be better to store id and header like this for example:

    array(
        "0" => "img1",
        "4" => "img4",
        "6" => "img6",
    );
    
    点赞 评论
  • dongyi4170
    dongyi4170 2013-09-16 18:30

    Arrays in PHP are actually hash tables behind the scenes, so accessing elements by key is extremely fast. If you can, change the way your array is created at the source to use the id (which I assume is unique) as the key, as already mentioned in other answers.

    To transform your current array to be indexed by id, you could use this code:

    $indexed = array();
    foreach($array as $element) {
        $indexed[$element['id']] = $element['header'];
    }
    // $indexed now resembles id => header
    

    You can then access header values in constant time using $indexed[$id].

    点赞 评论

相关推荐