Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 210
Irfanullah Jan Avatar asked Feb 19 '23 03:02

Irfanullah Jan


1 Answers

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
like image 66
berty Avatar answered Mar 05 '23 16:03

berty