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

天涯浪子 提交于 2019-11-30 22:53:23

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

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...

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.

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