简体   繁体   English

根据item中key的值获取数组中的item

[英]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?现在,如果想在不使用索引( $myArray[1] )的情况下获取第二项,而是使用name的值,即Some Other Name ,我该怎么做?

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.我查看了array_search() ,但找不到$myArray包含其他数组作为项目的示例。

you can use array_filter() function:您可以使用array_filter()函数:

<?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 :不完全确定您要做什么,但您可以在name上索引数组:

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

To do it once and have access to all name :做一次并可以访问所有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.所有其他解决方案将包括至少一次对您的阵列的完整循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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