How to find keys in multidimensional arrays in PHP?

WBOY
Release: 2016-09-06 08:57:08
Original
892 people have browsed it

My array is like this:

$arr = array(
'a' => Array(
'1' => '[Large]',
'2' => '[Small]',
'3' => ' [More]',
'4' => '[Less]',
)
'b' => Array(
'1' => '[You]',
'2' => ' [I]',
'3' => '[Her]',
'4' => '[It]',
)
)

I want [you] to be able to find 1 and also find the key b one level up.

array_search seems to only be able to search for one-dimensional arrays, please tell me.

Reply content:

My array is like this:

$arr = array(
'a' => Array(
'1' => '[Large]',
'2' => '[Small]',
'3' => ' [More]',
'4' => '[Less]',
)
'b' => Array(
'1' => '[You]',
'2' => ' [I]',
'3' => '[Her]',
'4' => '[It]',
)
)

I want [you] to be able to find 1 and also find the key b one level up.

array_search seems to only be able to search for one-dimensional arrays, please tell me.

Have you ever done a function similar to Infinitus classification? ? Do you know how the table for this function is designed? ?

For example: product classification table

<code>cat_id  cat_name  pid 
  1       test     0
  2       test1    0
  3       test3    0
  4       test4    1
  5       test5    2
  ......
</code>
Copy after login

This should be familiar to you. If I give you a category ID, what should I do if I want to find all its subcategories including itself? ? Or find all his parent classes including towers? ?

Regarding your question, if you have a way to format the key names of the multi-dimensional array into a structure similar to the table above, then you provide a value, find the key corresponding to the value in the array, and then use the formatted array Search inside and you'll get the results you want.

Traverse each sub-array. When traversing, remember to put the name of the sub-array into the cumulative variable. When you finally find it, output the cumulative variable.

In fact, it is to search for leaf nodes in the tree

I don’t know if this is what you want.

<code>foreach ($arr as $key=>$value) {
    $ikey = array_search('[你]', $value);
    if ($ikey) {
       echo $key,'--',$ikey,'<br>';
    }
}</code>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template