Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_filter and multidimensional array

Say I have an array such as:

$arr[] = array("id" => 11, "name" => "First");
$arr[] = array("id" => 52, "name" => "Second");
$arr[] = array("id" => 6, "name" => "Third");
$arr[] = array("id" => 43, "name" => "Fourth");

I would like to get the name correspondent to a certain ID so that I can do:

$name = findNameFromID(43);

and get, for instance, "Fourth".

I thought of using array_filter but I am a bit stuck on how to correctly pass a variable. I have seen questions such as this one but I don't seem to be able to extend the solution to a multidimensional array.

Any help?

like image 270
nico Avatar asked Jan 30 '12 22:01

nico


People also ask

What is the difference between the associative array and multidimensional array?

Associative array — An array where each key has its own specific value. Multidimensional array — An array containing one or more arrays within itself.

What is an multidimensional array?

Multidimensional arrays are an extension of 2-D matrices and use additional subscripts for indexing. A 3-D array, for example, uses three subscripts. The first two are just like a matrix, but the third dimension represents pages or sheets of elements.

What is a multidimensional array used for?

Multi-dimensional arrays are an extended form of one-dimensional arrays and are frequently used to store data for mathematic computations, image processing, and record management.


1 Answers

findNameFromID($array,$ID) {
     return array_values(array_filter($array, function($arrayValue) use($ID) { return $arrayValue['id'] == $ID; } ));
}

$name = findNameFromID($arr,43);
if (count($name) > 0) {
    $name = $name[0]['name'];
} else {
    echo 'No match found';
}

PHP 5.3.0 and above

EDIT

or variant:

findNameFromID($array,$ID) {
    $results = array_values(array_filter($array, function($arrayValue) use($ID) { return $arrayValue['id'] == $ID; } ));
    if (count($results) > 0) {
        return $name[0]['name'];
    } else {
        return FALSE;
    }
}

$name = findNameFromID($arr,43);
if (!$name) {
    echo 'No match found';
}

EDIT #2

And from PHP 5.5, we can use array_column()

findNameFromID($array, $ID) {
    $results = array_column($array, 'name', 'id');
    return (isset($results[$ID])) ? $results[$ID] : FALSE;
}
like image 130
Mark Baker Avatar answered Oct 19 '22 03:10

Mark Baker