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?

Answers


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

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


You can try this

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

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.


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

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


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....
        }
    }
}

Need Your Help

Connect to password protected wifi network using adb shell

android networking wifi adb access-point

I have an Android phone, and the goal is to connect the phone to a password protected wifi network.

Using BlockingCollection<>: OperationCanceledException, is there a better way?

c# multithreading blockingcollection

I'm making use of the (frankly great) BlockingCollection&lt;&gt; type for a heavily multithreaded, high-performance app.