简体   繁体   中英

Get item in array according to the value of a key within the item

Suppose I have an array like this:

$myArray = [
    [ 'id' => 1, 'name' => 'Some Name' ],
    [ 'id' => 2, 'name' => 'Some Other Name ] 
]

Now if want to get the second item without using the index ( $myArray[1] ), but instead by using the value of name which is Some Other Name , how do I do that?

I don't want to loop through the entire array just for one value, so how can I write this in a way that I don't explicitly loop through the array myself? I looked into array_search() , but couldn't find examples where $myArray contains additional arrays as items.

you can use array_filter() function:

<?php

$myArray = [
    ['id' => 1, 'name' => 'Some Name'],
    [
        'id' => 2, 'name' => 'Some Other Name'
    ]
];


$filterData = array_filter($myArray, function ($data) {
    return $data['name'] == "Some Other Name";
});
var_dump($filterData);
die;
?>

Not entirely sure what you're trying to do, but you can index the array on name :

echo array_column($myArray, null, 'name')['Some Other Name']['id'];  //echos 2

To do it once and have access to all name :

$result = array_column($myArray, null, 'name');

echo $result['Some Other Name']['id'];  // echos 2
echo $result['Some Name']['id'];        // echos 1

This is the simpliest solution:

$requiredItem = null;
foreach ($myArray as $item) {
    if ($item['name'] === 'Some Other Name') {
        $requiredItem = $item;
        // `break` allows you to STOP iterating over array
        break;
    }
}
print_r($requiredItem);

All other solutions will include full loop over your array at least once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM