Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top