【发布时间】:2014-03-12 17:16:57
【问题描述】:
我正在尝试自学多维数组的工作原理以及如何在 php 中比较和操作它们 我创建了两个具有相同方案但每个值不同的数组。
第一个数组
$datastuff1 = array( array( Ttitle => "rose",
Price => 1.25,
Number => 15
),
array( Ttitle => "daisy",
Price => 0.75,
Number => 25
),
array( Ttitle => "lilly",
Price => 1.75,
Number => 3
),
array( Ttitle => "orchid",
Price => 1.15,
Number => 7
)
);
第二个数组
$datastuff2 = array( array( Title => "rose",
Price => 1.25,
Number => 15
),
array( Title => "daisy",
Price => 0.75,
Number => 25
),
array( Title => "nettle",
Price => 2.75,
Number => 33
),
array( Title => "orchid",
Price => 1.15,
Number => 7
)
);
我现在想循环遍历两个数组和foreach 两个数组中匹配的项目(使用标题作为键)添加到一个新的匹配数组,并且对于两个数组中不匹配的每个项目都添加到我的数组不匹配
这是我的代码
$matchingarray = array();
$notmatchingarray = array();
foreach($datastuff1 as $data1){
foreach($datastuff2 as $data2){
if($data2['Title']== $data1['Ttitle'])
{
$matchingarray[] = $data1;
}
else {
$notmatchingarray[] = $data1;
}
}
}
但是当我使用
输出数组的内容时 echo "<pre>";
print_r($notmatchingarray);
echo "</pre>";
我得到输出
Array
(
[0] => Array
(
[Ttitle] => rose
[Price] => 1.25
[Number] => 15
)
[1] => Array
(
[Ttitle] => rose
[Price] => 1.25
[Number] => 15
)
[2] => Array
(
[Ttitle] => rose
[Price] => 1.25
[Number] => 15
)
[3] => Array
(
[Ttitle] => daisy
[Price] => 0.75
[Number] => 25
)
[4] => Array
(
[Ttitle] => daisy
[Price] => 0.75
[Number] => 25
)
[5] => Array
(
[Ttitle] => daisy
[Price] => 0.75
[Number] => 25
)
[6] => Array
(
[Ttitle] => lilly
[Price] => 1.75
[Number] => 3
)
[7] => Array
(
[Ttitle] => lilly
[Price] => 1.75
[Number] => 3
)
[8] => Array
(
[Ttitle] => lilly
[Price] => 1.75
[Number] => 3
)
[9] => Array
(
[Ttitle] => lilly
[Price] => 1.75
[Number] => 3
)
[10] => Array
(
[Ttitle] => orchid
[Price] => 1.15
[Number] => 7
)
[11] => Array
(
[Ttitle] => orchid
[Price] => 1.15
[Number] => 7
)
[12] => Array
(
[Ttitle] => orchid
[Price] => 1.15
[Number] => 7
)
)
所以在我看来,它好像循环了三遍(匹配的项目数量),每次都将匹配的项目放入数组中。
我想要的是非匹配数组中不匹配的所有项目(使用标题作为键)以及匹配数组中匹配的项目。我想我遗漏了一些非常明显的东西。
任何帮助都会很重要 考虑迈克
【问题讨论】:
标签: php arrays multidimensional-array