繁体   English   中英

如何使用PHP搜索数组中的键值是否存在于另一个数组中?

[英]How to search if the key value in an array exists in another array, using PHP?

我需要帮助。 我有两个数组。 我需要检查第二个数组中是否存在第一个数组中的值。 数组如下:

$maindata=array(array('id'=>3),array('id'=>7),array('id'=>9));
$childata=array(array('id'=>7),array('id'=>11),array('id'=>3),array('id'=>123));

在这里,我需要检查第一个数组中的每个值是否存在于第二个数组中。 如果是,则应每次返回true否则返回false

在这里,您可以将in_array()用于PHP。

$maindata=array( array('id'=>3),array('id'=>7),array('id'=>9) );
$childata=array( array('id'=>7),array('id'=>11),array('id'=>3),array('id'=>123) );

foreach( $maindata as $key => $value )
{
  if( in_array( $value, $childata ) )
  {
    echo true;
  }
  else
  {
    echo false;
  }
}

您也可以删除全部内容,并替换为一行。

echo ( in_array( $value, $childata ) ? true : false );

参考-http : //php.net/manual/zh/function.in-array.php https://code.tutsplus.com/tutorials/the-ternary-operator-in-php--cms-24010

要检查数组是否包含值:

if (in_array($value, $array)) {
    // ... logic here
}

要检查数组是否包含某个键:

if (array_key_exists($key, $array)) {
    // ... logic here
}

资源资源

以下代码仅在主数组的所有元素都存在于第二个数组中时才返回true ,否则返回false

$maindata=array(array('id'=>3),array('id'=>7),array('id'=>9));
$childata=array(array('id'=>3),array('id'=>7),array('id'=>11),array('id'=>123));

$match = 0;
foreach( $maindata as $key => $value ) {
  if( in_array( $value, $childata ) ) {
    $match++;
  }
}
if($match == count($maindata)){
    // return true;
} else {
    // return false;
}

使用array_intersect

if(!empty(array_intersect($childata, $maindata)))
{
   //do something
}

要么

$result  = count(array_intersect($childata, $maindata)) == count($childata);

使用array_columnarray_intersect

$first = array_column($maindata, 'id');
$second = array_column($childata, 'id');

//If intersect done, means column are common
if (count(array_intersect($first, $second)) > 0) {
  echo "Value present from maindata in childata array.";
}
else {
  echo "No values are common.";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM