如何从匹配的两个数组中获取键值?

时间:2019-04-24 13:41:54

标签: php arrays

我有2个数组,我试图找到任何匹配项,并从$ array_full返回'url。

我尝试了array_intersect($ array_full,$ array_ids),但是它不起作用。

$array_full = array
(
        Array
        (
            '@attributes' => Array
                (
                    'topicid' => 102000,
                    'url' => 'Velkommen.htm',
                    'alias' => 'Velkommen'
                )
        ),
        Array
        (
            '@attributes' => Array
                (
                    'topicid' => 130313,
                    'url' => 'WStation/WAS_Indstillinger.htm',
                    'alias' => 'WAS_Indstillinger'
                )
        ),
        Array
        (
            '@attributes' => Array
                (
                    'topicid' => 130315,
                    'url' => 'SPedestal/Applikationer/LoadSharing/Indstillinger.htm',
                    'alias' => 'LOS_Indstillinger'
                )
        ),
        Array
        (
            '@attributes' => Array
                (
                    'topicid' => 130312,
                    'url' => 'WStation/WAS_Indstillinger.htm',
                    'alias' => 'WAS_Indstillinger'
                )
        )
);

$array_ids = array('130312', '130315');

我希望获得一个匹配的网址数组,例如:

array('WStation/WAS_Indstillinger.htm','SPedestal/Applikationer/LoadSharing/Indstillinger.htm')

3 个答案:

答案 0 :(得分:3)

几个简单的foreach循环似乎是最简单的方法

$results = [];

foreach ( $array_full as $a ) {
    foreach ( $a as $item ) {
        if ( in_array($item['topicid'], $array_ids) ) {
            $results[] = $item['url'];
        }        
    }
}
print_r($results);

结果

Array
(
    [0] => SPedestal/Applikationer/LoadSharing/Indstillinger.htm
    [1] => WStation/WAS_Indstillinger.htm
)

答案 1 :(得分:2)

您必须在foreach内进行foreach才能找到与ID匹配的项目。 诸如此类(未经测试,可能包含一些错字)。

        foreach($array_ids as $id) {
            foreach($array_full as $key => $fullItem) {
                   if($fillItem['@attributes']['topicid'] != $id) {
                       continue;
                   }
                   //do what you need with $fullItem array
                   $key; // this is the key you want
            }
        }

答案 2 :(得分:0)

您可以使用array_mapin_array来获取URL的

$result = [];
array_map(function($v) use ($array_ids,&$result){
$result[] = in_array($v['@attributes']['topicid'], $array_ids) ? $v['@attributes']['url'] : '';
}, $array_full);

结果:-

echo '<pre>';
print_r(array_filter($result));

Array
(
  [2] => SPedestal/Applikationer/LoadSharing/Indstillinger.htm
  [3] => WStation/WAS_Indstillinger.htm
)