search

Home  >  Q&A  >  body text

How does PHP determine whether the key values ​​in the array use the same key name and output the current key value with the same key name?

<?php
$arr=array(
0=>array(
    1=>'鼠',
    15=>'牛',
    29=>'虎'
),
30=>array(
    50=>'兔',
    59=>'龙',
    65=>'蛇'
);
?>

The code is as above, how to determine whether 50, 59, and 65 belong to the same key name and output the text under all 30 key names? Thank you in advance. I haven’t researched this issue for a day and I don’t know how to judge.

typechotypecho2735 days ago863

reply all(1)I'll reply

  • 学习ing

    学习ing2017-06-24 09:44:20

    $target = [50, 59, 65];
    foreach($arr as $index => $value) { // 遍历整个$arr
        $keys = array_keys($value); // 获取对应项的键值
    
        $check = true; // 默认为真,如果下面遍历中出现一个假值则为假,否则真值表示所有的目标键名都在此项中
    
        foreach($target as $target_key) { // 遍历所有的目标键名
            if(!in_array($target_key, $keys)) { // 如果发现目标键名不在当前项键名$keys中,则设置$check为假值,并直接跳出
                $check = false;
                break;
            }
        }
    
        if($check) { // 通过了键名检测,那么这就是要找的项,输出
            print_r($index);
            print_r($value);
        }
    }

    Output:

    30Array ( [50] => 兔 [59] => 龙 [65] => 蛇 )

    (Since the code uses print_r without adding line breaks, the content is all displayed on one line)

    reply
    0
  • Cancelreply