我需要匹配两个不同数组的值。如果来自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;
答案 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;
}