Home php Quick search in a multidimensional array

Quick search in a multidimensional array

Author

Date

Category

On the arms of such a content:

array (
[Show] = & gt; Array.
  (
  [0] = & gt; Array.
      (
        [Name] = & gt; Good dinosaur
        [ID] = & gt; 3777.
        [Alias] = & gt; Dobrii-Dinozavr-the-Good-Dinosaur
       )
  [1] = & gt; Array.
      (
        [Name] = & gt; Star Wars: Awakening Force
        [ID] = & gt; 3821.
        [Alias] = & gt; Zvezdnie-Voini-ProBuzhdenie-Sili-Star-Wars-The-Force-Awakens
      )
  [2] And so on ...

Tell me how best to get [id] If there is only [Alias] ?


Answer 1, Authority 100%

for php & gt; 5.5.0 in theory you can write like this:

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

For a common case and possibly for 5.5.0 will work faster – to constrain an array in advance with indexes by Alias ​​and content – ID .

If you need to get different fields, based on alias, then build an array with keys by Alias ​​and values ​​- numbers in the source array. Those. Something like this:

& lt;? php
$ ARR = Array (Array ("Name" = & gt; "Good dinosaur", "id" = & gt; 3777, "Alias" = & gt; "dobrii-dinozavr-the-good-dinosaur"),
      Array ("Name" = & gt; "Star Wars: Awakening Force", "id" = & gt; 3821,
        "Alias" = & gt; "Zvezdnie-Voini-ProBuzhdenie-Sili-Star-Wars-the-Force-awakens")
     );
$ index = array ();
Foreach ($ AR AS $ k = & gt; $ V)
{
 $ index [$ V ['alias']] = $ k;
}
Print $ Arr [$ Index ["dobrii-dinozavr-the-good-dinosaur"]] ["id"];
? & gt;

If the search occurs often in many challenges of the script, and getting a new source array is rare. That record information in the database or at least prepare an index or converted array in advance and put it somewhere, for example, using Serialize .

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions