Get the sub array in a bidimensional array having

2019-02-14 06:13发布

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.

3条回答
冷血范
2楼-- · 2019-02-14 06:54

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楼-- · 2019-02-14 07:00

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.

查看更多
一纸荒年 Trace。
4楼-- · 2019-02-14 07:04

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
查看更多
登录 后发表回答