php 对多维数组使用 array_search

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7694843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:11:52  来源:igfitidea点击:

using array_search for multi dimensional array

phparraysmultidimensional-array

提问by Sikret Miseon

using array_search in a 1 dimensional array is simple

在一维数组中使用 array_search 很简单

$array = array("apple", "banana", "cherry");
$searchValue = "cherry";
$key = array_search($searchValue, $array);

echo $key;

but how about an multi dimensional array?

但是多维数组呢?

    #RaceRecord

    [CarID] [ColorID] [Position]
[0]    1        1         3
[1]    2        1         1
[2]    3        2         4
[3]    4        2         2
[4]    5        3         5

for example i want to get the index of the car whose position is 1. How do i do this?

例如,我想获取位置为 1 的汽车的索引。我该怎么做?

回答by SRB

In php 5.5.5 & later versions, you can try this

在 php 5.5.5 及以后的版本中,你可以试试这个

$array_subjected_to_search =array(
array(
        'name' => 'flash',
        'type' => 'hero'
    ),

array(
        'name' => 'zoom',
        'type' => 'villian'
    ),

array(
        'name' => 'snart',
        'type' => 'antihero'
    )
);
$key = array_search('snart', array_column($array_subjected_to_search, 'name'));
var_dump($array_subjected_to_search[$key]);

Output:

输出:

array(2) { ["name"]=> string(5) "snart" ["type"]=> string(8) "antihero" }

working sample : http://sandbox.onlinephpfunctions.com/code/19385da11fe0614ef5f84f58b6dae80bd216fc01

工作示例:http: //sandbox.onlinephpfunctions.com/code/19385da11fe0614ef5f84f58b6dae80bd216fc01

Documentation about array_column can be found here

可以在此处找到有关 array_column 的文档

回答by Amber

function find_car_with_position($cars, $position) {
    foreach($cars as $index => $car) {
        if($car['Position'] == $position) return $index;
    }
    return FALSE;
}

回答by HCDINH

You can try this

你可以试试这个

array_search(1, array_column($cars, 'position'));

回答by Loupax

Hooray for one-liners!

单行者万岁!

$index = array_keys(array_filter($array, function($item){ return $item['property'] === 'whatever';}))[0];

Let's make it more clear:

让我们说得更清楚:

array_filter(
    $array, 
    function ($item) {
        return $item['property'] === 'whatever';
    }
); 

returns an array that contains all the elements that fulfill the condition in the callback, while maintaining their original array keys. We basically need the key of the first element of that array.

返回一个数组,其中包含满足回调中条件的所有元素,同时保留其原始数组键。我们基本上需要该数组的第一个元素的键。

To do this we wrap the result in an array_keys()call and get it's first element. This specific example makes the assumption that at least one matching element exists, so you might need an extra check just to be safe.

为此,我们将结果包装在一个array_keys()调用中并获取它的第一个元素。此特定示例假设至少存在一个匹配元素,因此您可能需要额外检查以确保安全。

回答by Michael J. Calkins

I basically 'recreated' underscore.js's findWhere method which is to die for.

我基本上“重新创建”了 underscore.js 的 findWhere 方法,这是为之而死。

The function:

功能:

function findWhere($array, $matching) {
    foreach ($array as $item) {
        $is_match = true;
        foreach ($matching as $key => $value) {

            if (is_object($item)) {
                if (! isset($item->$key)) {
                    $is_match = false;
                    break;
                }
            } else {
                if (! isset($item[$key])) {
                    $is_match = false;
                    break;
                }
            }

            if (is_object($item)) {
                if ($item->$key != $value) {
                    $is_match = false;
                    break;
                }
            } else {
                if ($item[$key] != $value) {
                    $is_match = false;
                    break;
                } 
            }
        }

        if ($is_match) {
            return $item;   
        }
    }

    return false;
}

Example:

例子:

$cars = array(
    array('id' => 1, 'name' => 'Toyota'),
    array('id' => 2, 'name' => 'Ford')
);

$car = findWhere($cars, array('id' => 1));

or

或者

$car = findWhere($cars, array(
    'id' => 1,
    'name' => 'Toyota'
));

I'm sure this method could easily reduce LOC. I'm a bit tired. :P

我相信这种方法可以轻松减少 LOC。我有点累了。:P

回答by Rukmi Patel

actually all array functions are designed for single dimension array.You always need to keep in mind that you are applying it on single dimension array.

实际上所有的数组函数都是为一维数组设计的。你总是需要记住你是将它应用于一维数组。

function find_car_with_position($cars, $position) {
    for($i=0;$i<count($cars);$i++){
        if(array_search($search_val, $cars[$i]) === false){
             // if value not found in array.....
        }  
        else{
            // if value is found in array....
        }
    }
}