Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 340
Sikret Miseon Avatar asked Oct 08 '11 04:10

Sikret Miseon


People also ask

Can C language handle multidimensional arrays?

In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];

How can I get multidimensional array in PHP?

Accessing multidimensional array elements: There are mainly two ways to access multidimensional array elements in PHP. Elements can be accessed using dimensions as array_name['first dimension']['second dimension']. Elements can be accessed using for loop. Elements can be accessed using for each loop.

Which library can be used to support multidimensional array?

numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object and tools for working with these arrays.


2 Answers

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

like image 185
SRB Avatar answered Oct 08 '22 23:10

SRB


function find_car_with_position($cars, $position) {     foreach($cars as $index => $car) {         if($car['Position'] == $position) return $index;     }     return FALSE; } 
like image 37
Amber Avatar answered Oct 08 '22 22:10

Amber