匹配两个不同阵列的值和&重建

时间:2014-02-16 17:00:56

标签: php arrays

我需要匹配两个不同数组的值。如果来自position的{​​{1}}位于array_1,则指定位置&对新数组的描述。如果array_2中的position不在array_1中,请将array_2的空描述分配给新数组。

由于第二个position,我的PHP代码(如下)无效。它覆盖了新数组(foreach)。它只写了最后的描述。

array_1:

position_array

array_2:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 6
    [5] => 12
)

PHP:

Array
(
    [0] => Array
        (
            [position] => 2
            [description] => Text 1
        )

    [1] => Array
        (
            [position] => 4
            [description] => Text 2
        )

    [2] => Array
        (
            [position] => 6
            [description] => Text 3
        )

    [3] => Array
        (
            [position] => 12
            [description] => Text 4
        )
)

结果:

print_r($_POST['position']);
print_r($_POST['position_desc']);

$position=$_POST['position'];
# Check if there was POST data sent.
if(isset($_POST['position_desc']))
{
    # Create an empty array.
    $position_array=array();
    # Loop through the user's positions.
    foreach($position as $position_key=>$position_value)
    {
        foreach($_POST['position_desc'] as $desc_key=>$position_desc)
        {
            echo $position_value.' -> '.$position_desc['position'].' - ';
            if($position_value==$position_desc['position'])
            {
                echo 'MATCH - Assign Desc<br>';
                # Assign the position and description to the array.
                $position_array[$position_key]=array('position'=>$position_value, 'description'=>$position_desc['description']);
            }
            else
            {
                echo 'NO MATCH - Assign empty Desc<br>';
                # Assign the position and description to the array.
                $position_array[$position_key]=array('position'=>$position_value, 'description'=>'');
            }
        }
    }
    print_r($position_array);
    exit;

1 个答案:

答案 0 :(得分:1)

使用break结束第二个foreach并避免覆盖。

$newArray = array();
foreach ($array1 as $position) {
    $temp = array();
    foreach ($array2 as $key => $value) {
        $temp = array(
            'position' => $position,
            'description' => ""
        );
        if ($value['position'] == $position) {
            $temp['description'] = $value['description'];
            unset($array2[$key]);
            break;
        }
    }
    $newArray[] = $temp;
}