Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

php - using array_search for multi dimensional array

using array_search in a 1 dimensional array is simple

$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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In php 5.5.5 & later versions, you can try this

$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

Documentation about array_column can be found here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...