Quick search in a multidimensional array

On the hands of an array of such content:

Array (
[show] => Array
    (
    [0] => Array
            (
                [name] => Добрый динозавр
                [id] => 3777
                [alias] => dobrii-dinozavr-the-good-dinosaur
             )
    [1] => Array
            (
                [name] => Звёздные войны: Пробуждение силы
                [id] => 3821
                [alias] => zvezdnie-voini-probuzhdenie-sili-star-wars-the-force-awakens

            )
    [2] и так далее...

Tell me how best to get [id] if there is only [alias]?

Author: LEQADA, 2016-01-06

1 answers

For php>5.5.0, in theory, you can write this:

$key = array_search("dobrii-dinozavr-the-good-dinosaur", array_column($arr, 'alias'));
echo $arr[$key]["id"];

For the general case, and possibly for 5.5.0, it will work faster to post an array with indexes by alias and contents by id in advance.

If you need to get different fields based on aliases, then build an array with keys by alias and values-numbers in the original array. I.e. something like that:

<?php
$arr=array(array ("name" => "Добрый динозавр","id" => 3777,"alias" => "dobrii-dinozavr-the-good-dinosaur"),
           array ("name" => "Звёздные войны: Пробуждение силы","id" => 3821,
                "alias" => "zvezdnie-voini-probuzhdenie-sili-star-wars-the-force-awakens")
          );
$index=array();
foreach($arr as $k => $v)
{
 $index[$v['alias']]=$k;
}
print $arr[$index["dobrii-dinozavr-the-good-dinosaur"]]["id"];
?>

If the search occurs frequently in many script calls, and getting a new source array is rare. write the information to the database, or at least prepare an index or converted array in advance and put it somewhere, for example, using serialize.

 6
Author: Mike, 2016-01-06 14:02:31