两个数组中的常用值

时间:2016-02-23 06:59:08

标签: php arrays multidimensional-array

我有两个数组 -

$x = [['email' => 'abc@gmail.com', 'id' => [1,2,3]],
      ['email' => 'xyz@gmail.com', 'id' => [4,5]]]
$y = ['email' => 'abc@gmail.com']

我必须在$x数组中返回两个集合中的公共电子邮件以及ID。

输出应为 -

$z = [['email' => 'abc@gmail.com', 'id' => [1,2,3]]

怎么做? array_intersect?但是对于array_intersect,两个数组都应该具有相同数量的键。

2 个答案:

答案 0 :(得分:4)

您需要使用foreach循环以传统方式执行此操作:

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <?php print $user_picture; ?>

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
   <div class="field-name-field-graphic"> <?php print render($content['field_name_field_graphic']);?> </div>
    <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($display_submitted): ?>
    <div class="submitted">
      <?php print $submitted; ?>
    </div>
  <?php endif; ?>

  <div class="content"<?php print $content_attributes; ?>>
    <?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      hide($content['field_name_field_graphic']);
      print render($content);
    ?>
  </div>

  <?php print render($content['links']); ?>

  <?php print render($content['comments']); ?>

</div>

输出:

$x = [
    ['email' => 'abc@gmail.com', 'id' => [1, 2, 3]],
    ['email' => 'xyz@gmail.com', 'id' => [4, 5]]
];
$y = array('email' => 'abc@gmail.com');

$z = array();

foreach($x as $arr){
    if(in_array($arr['email'],$y) !== false){
        $z[] = $arr;
    }
}

print_r($z);

答案 1 :(得分:0)

您可以将array_filter()与匿名函数一起使用,并通过use指令传递 needle 值:

$x = [
  ['email' => 'abc@gmail.com', 'id' => [1,2,3]],
  ['email' => 'xyz@gmail.com', 'id' => [4,5]]
];

$y = ['email' => 'abc@gmail.com'];

$matched = array_filter($x, function($item) use($y) {
  return $item['email'] === $y['email'];
});
相关问题