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?
In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];
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.
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.
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
function find_car_with_position($cars, $position) { foreach($cars as $index => $car) { if($car['Position'] == $position) return $index; } return FALSE; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With