2个数组相同的键和值检查来自一个数组的值是否在这里

时间:2015-06-26 23:02:20

标签: php arrays if-statement

我有2个数组合并到一个数组,现在我想检查数组$b中的值1是否然后在foreach中向$b添加特殊内容值。

但在下面的示例中,将内容添加到$s$b

$s = array(1,2,3,4,5);
$b = array(1,2,3,4);

 $one = array_merge($s,$b);
 $arr = array_chunk($one, 1);
foreach($arr as $k=>$v){
if(in_array($arr[$k][0],$b)){
    echo "c";
}
     echo $arr[$k][0]."<br>";
}

输出

c1
c2
c3
c4
5
c1
c2
c3
c4

我想要那个输出

1
2
3
4
5
c1
c2
c3
c4

2 个答案:

答案 0 :(得分:0)

很简单。你只需要检查 if condition 。如果循环重复的次数大于数组$ s的长度,则回显“c”;

$s = array(1,2,3,4,5);
$b = array(1,2,3,4);

$one = array_merge($s,$b);
$arr = array_chunk($one, 1);
$s_length = count($s);
$i = 1;
foreach($arr as $k=>$v){
    // Check if the loop has been repeated more than the length of the array $s
    if($i > $s_length){
        echo "c";
    }
    echo $arr[$k][0]."<br>";
    $i++;
}

答案 1 :(得分:0)

我不确切地知道这是不是你想要的,但是:

$s = array(1,2,3,4,5);
$b = array(1,2,3,4);

$arr = array_diff($s, $b);

// Search differences between diff() and $s
$cs= "";
$cb= "";
// If array have semantical keys we'll do an array_values()
foreach ( array_values($arr) as $k => $v ){ 
    // If $cs is actually set as 'c'
    if ( "c"!=$cs ){
        // If a value in the diff() array are not in s => $cs = 'c'
        $cs= ( !in_array( $v, $s ,true ))? "c": "";
    }
    // If $cb is actually set as 'c'
    if ( "c"!=$cb ){
        $cb= ( !in_array( $v, $b ,true ))? "c" : "";
    }
}

// Print each array values with associated $c
foreach ( $s as $k => $v ){ 
    echo "<br>$cs$v"    ;
}
foreach ( $b as $k => $v ){ 
    echo "<br>$cb$v"    ;
}

输出:

1
2
3
4
5
c1
c2
c3
c4