Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...