dopii22884
2017-03-14 13:57
浏览 41
已采纳

将array_intersect与多维数组和不同的键一起使用

Having this array ($firstArray):

array(3) {
  [0]=>
  array(2) {
    ["Name"]=>
    string(3) "foo"
    ["id"]=>
    string(4) "1064"
  }
  [1]=>
  array(2) {
    ["Name"]=>
    string(3) "boo"
    ["id"]=>
    string(4) "1070"
  }
  [2]=>
  array(2) {
    ["Name"]=>
    string(3) "bar"
    ["id"]=>
    string(4) "1081"
 }

And this one ($secondArray):

array(2) {
  [0]=>
  string(4) "1064"
  [1]=>
  string(4) "1081"
}

How can I use array_intersect on these inner arrays?

I tried array_intersect($firstArray, $secondArray); which is not working.

My desired output would be:

array(2) {
  [0]=>
  array(2) {
    ["Name"]=>
    string(3) "foo"
    ["id"]=>
    string(4) "1064"
  }
  [1]=>
  array(2) {
    ["Name"]=>
    string(3) "bar"
    ["id"]=>
    string(4) "1081"
 }

PS: I'm using PHP 5.2 (I cant update the version as it's not my own machine)

Thanks in advance.

图片转代码服务由CSDN问答提供 功能建议

拥有此数组( $ firstArray ): < pre> array(3){ [0] =&gt; array(2){ [“Name”] =&gt; string(3)“foo” [“id” ] =&gt; string(4)“1064” } [1] =&gt; array(2){ [“Name”] =&gt; string(3)“boo” [“id”] =&gt; string(4)“1070” } [2] =&gt; array(2){ [“Name”] =&gt; string (3)“bar” [“id”] =&gt; string(4)“1081” }

这一个(<) code> $ secondArray ):

  array(2){
 [0] =&gt; 
 string(4)“1064”
 [1  ] =&gt; 
 string(4)“1081”
} 
   
 
 

如何在这些内部数组上使用 array_intersect

我尝试了 array_intersect($ firstArray,$ secondArray); 无效。

我想要的输出是 :

  array(2){
 [0] =&gt; 
 array(2){
 [“Name”] =&gt; 
 string(3  )“foo”
 [“id”] =&gt; 
 string(4)“1064”
} 
 [1] =&gt; 
 array(2){\  n [“名称”] =&gt; 
字符串(3)“bar”
 [“id”] =&gt; 
 string(4)“1081”
} 
    
 
 

PS:我使用的是PHP 5.2(我无法更新版本,因为它不是我自己的机器)

提前致谢。 < / DIV>

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dtuy84033 2017-03-14 14:05
    已采纳

    You can't use array_intersect on two arrays with different structures. To achieve your goal, you have to loop through your first array and check if the id value is in the second array, as such :

    $outputArray = array();
    
    foreach ($firstArray as $value) {
        if (in_array($value['id'], $secondArray))
            $outputArray[] = $value;
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题