数组合并:使用foreach?
问题描述:
我有2个数组:数组合并:使用foreach?
$im=explode(",", $data['products']);
$imi=explode(",", $data['period']);
其相关联:
$data['products'] = balon,globo,sesta
$data['period'] = 1,1,2
所以当我合并的结果,它是:
Array ([0] => DS Basic [1] => DS Pro [2] => DS Start [3] => 1 [4] => 1 [5] => 2)
的问题是,我需要它是像这样关联:
DS Basic = 1 , DS Pro = 1 , DS Start = 2
我正在使用array_merge($im,$imi)
我该如何使用foreach
来做到这一点? 我想这样的:
Array ([0] => DS Basic [1] => DS Pro [2] => DS Start)
Array ([0] => 1 [1] => 1 [2] => 2)
所以,当我使用它,它可以像
using foreach
DS basic has a period of 1
DS pro has a period of 1
DS start has a period of 2
答
你需要的是组合,而不是合并)具有看看PHP对array_combine手册。
请不考虑你的期望的结果保存一组数据作为键(在你的榜样产品阵列值),你是不是想有重复值,否则你将失去他们
+1
那是因为我在寻找谢谢它的工作 –
+0
你最不欢迎:) – Ali
答
您可以修复合并的结果如下:
$merged = array_merge($im,$imi);
$period = array();
// Loop through the merged items
foreach ($merged as $k=>$v) {
// Check if the value is an integer
if ((int)$v) {
// Move this value to the period array
$period[] = $v;
// Remove it from the merged array
unset($merged[$k]);
}
}
// Reindex the merged array to revalue the keys
$merged = array_values($merged);
// Test the output
echo '<h1>Merged Array:</h1>';
echo '<pre>';
echo print_r($merged);
echo '</pre>';
echo '<h1>Excess Array:</h1>';
echo '<pre>';
echo print_r($period);
echo '</pre>';
exit;
答
$merged = array();
if (count($im) != count($imi)) {
print "custom merging is not possible...";
}
else {
for($i=0 ; $i<count($im) ; $i++) {
$merged[$im[$i]] = $imi[$i];
}
}
答
你可以做foreach
$newArr = [];
foreach($im $key => $val)
{
$newArr[] = [$val[0] => $imi[$key][0], $val[1] => $imi[$key][1], $val[2] => $imi[$key][2]];
}
print_r($newArr);
或者结合起来:
$result = array_combine($im, $imi);
你能'的print_r( $ IM)'? – aldrin27