duankuai6586
duankuai6586
2016-01-14 21:35

在PHP中检查两个数组的每个值

已采纳

I want to check 2 values of array below and replace value on Array B with 0 or 1 values if that each array values is match or not with Array A. Here is my array data:

Array A:

enter image description here

Array (
    [a1] => 2
    [a2] => 2
    [a3] => 3 )

Array B:

enter image description here

Array (
[0] => Array
    (
        [a1] => 2
        [a2] => 1
        [a3] => 3
        [so] => 7
    )

[1] => Array
    (
        [a1] => 3
        [a2] => 2
        [a3] => 2
        [so] => 8
    )

[2] => Array
    (
        [a1] => 1
        [a2] => 3
        [a3] => 4
        [so] => 9
    ) )

And this is the output what i expect:

enter image description here

Any idea how to do this in PHP? Because i'm still confused how to combine array_diff or array_intersect with foreach loop

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doulu2011 doulu2011 5年前

    Maybe not the most elegant solution, but it works:

    $a = array
        (
            'a1' => 2,
            'a2' => 2,
            'a3' => 3
        );
    
    $b = array ( 
        array
        (
            'a1' => 2,
            'a2' => 1,
            'a3' => 3,
            's0' => 7
        ),
    
        array
        (
            'a1' => 3,
            'a2' => 2,
            'a3' => 2,
            's0' => 8
        ),
    
        array
        (
            'a1' => 1,
            'a2' => 3,
            'a3' => 4,
            's0' => 9
        ) );
    
    
    $c = array ();
    
    $i=0;
    foreach ($b as $b_row)
    {
        $c[$i]['a1'] = ( $a['a1'] == $b_row['a1'] ) ? 1 : 0;
        $c[$i]['a2'] = ( $a['a2'] == $b_row['a2'] ) ? 1 : 0;
        $c[$i]['a3'] = ( $a['a3'] == $b_row['a3'] ) ? 1 : 0;
        $c[$i]['s0'] = $b_row['s0'];
        $i++;
    }
    

    or a bit more compact:

    $i=0;
    foreach ($b as $b_row)
    {
        foreach ($b_row as $b_cell => $value)
        {
            if (isset ($a[$b_cell])) 
            {
                $c[$i][$b_cell] = ( $a[$b_cell] == $value ) ? 1 : 0;
            }
            else 
            {
                $c[$i][$b_cell] = $value;
            }
        }
        $i++;
    }
    
    点赞 评论 复制链接分享
  • doucheng1891 doucheng1891 5年前

    Can't test just now but it maybe something like this

    foreach ($arrayB as &$ar)
       foreach ($ar as $k => &$v)
          if (isset($arrayA[$k]) 
              $v = ($v == $arrayA[$k] ? 1 :0);
    
    点赞 评论 复制链接分享

相关推荐