Get the sub array in a bidimensional array having a particular key/value pair

蹲街弑〆低调 提交于 2019-12-19 03:59:30

问题


I have a large PHP array, similar to:

$list = array(
    array(
        'id'     = '3243'
        'link'   = 'fruits'
        'lev'    = '1'
    ),
    array(
        'id'     = '6546'
        'link'   = 'apple'
        'lev'    = '2'
    ),
    array(
        'id'     = '9348'
        'link'   = 'orange'
        'lev'    = '2'
    )
)

I want to get the sub-array which contains a particular id.

Currently I use the following code:

$id = '3243'
foreach ($list as $link) {
    if (in_array($id, $link)) {
        $result = $link;
    }
}

It works but I hope there is a better way of doing this.


回答1:


You can

  • write $link['id']==$id instead of in_array($id, $link) whitch will be less expensive.
  • add a break; instruction after $result = $link; to avoid useless loops



回答2:


While this answer wouldn't have worked when the question was asked, there's quite an easy way to solve this dilemma now.

You can do the following in PHP 5.5:

$newList = array_combine(array_column($list,'id'),$list);

And the following will then be true:

$newList[3243] = array(
                         'id'   = '3243';
                         'link' = 'fruits'; etc...



回答3:


The simplest way in PHP 5.4 and above is a combination of array_filter and the use language construct in its callback function:

function subarray_element($arr, $id_key, $id_val = NULL) {
  return current(array_filter(
    $arr,
    function ($subarr) use($id_key, $id_val) {
      if(array_key_exists($id_key, $subarr))
        return $subarr[$id_key] == $id_val;
    }
  ));
}
var_export(subarray_element($list, 'id', '3243')); // returns:
// array (
//   'id' => '9348',
//   'link' => 'orange',
//   'lev' => '2',
// )

current just returns the first element of the filtered array. A few more online 3v4l examples of getting different sub-arrays from OP's $list.



来源:https://stackoverflow.com/questions/13933454/get-the-sub-array-in-a-bidimensional-array-having-a-particular-key-value-pair

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!