johannesbe_
johannesbe_

Reputation: 13

Search a 3d array and return the key path of the first matching value

I used a php ics parser to extract data from some ics files into an array, which has a basic structure like this:

[a] => Array (

   [foo] => Array (

      [0] => 01-02-2018 
      [1] => 02-02-2018
      ...

      )
   [bar] => Array (

      [0] => 19-03-2018
      [1] => 20-03-2018
      ...

      )
   ...
)

[b] => Array (

   [foo] => Array (

      [0] => 31-01-2019
      ...

      )
   [bar] => Array(

      [0] => 14-02-2019
      ...

      )
   ...
)

What I want to be able to do is pretty simple:

Input: 19-03-2018.

Output: "bar a".

I looked up array_search, in_array and other common solutions but I couldn't wrap my head around how to use them in this particular case.

Notes:

Upvotes: 0

Views: 43

Answers (1)

u_mulder
u_mulder

Reputation: 54831

As you have array of arrays of arrays you need to iterate with two foreachs:

foreach ($Array as $level1_key => $level1_value) {
    foreach ($level1_value as $level2_key => $level2_value) {
        if (in_array('19-03-2018', $level2_value)) {
            echo 'Value found in ' . $level1_key . ' ' . $level2_key;
            // stop both `foreach`s
            break 2;
        }
    }
}

Upvotes: 1

Related Questions