我试图将两个或多个数组中的一些数字添加到一个数组中。我的问题是,它总是添加另一个索引。
源数组如下所示:
array(
(int) 0 => array(
'Sale' => array(
'id' => '1',
'market_id' => '1',
'product_ids' => '1,2,3,4,5,6,7,8',
'date_and_time' => '2014-12-28 00:00:00',
'money_spent' => '2344',
'points_given' => '213'
)
),
(int) 1 => array(
'Sale' => array(
'id' => '2',
'market_id' => '1',
'product_ids' => '44,3,32,23,12,32',
'date_and_time' => '2014-12-28 15:25:38',
'money_spent' => '123',
'points_given' => '2'
)
)
)
用于合并数组并从product_ids字段中分解数字的PHP代码
$sales=array();
foreach ($sales_detailed as $sale_detailed): {
$sale_detailed_ids=explode( ',', $sale_detailed['Sale']['product_ids'] );
array_push($sales, $sale_detailed_ids);
} endforeach;
结果是
array(
(int) 0 => array(
(int) 0 => '1',
(int) 1 => '2',
(int) 2 => '3',
(int) 3 => '4',
(int) 4 => '5',
(int) 5 => '6',
(int) 6 => '7',
(int) 7 => '8'
),
(int) 1 => array(
(int) 0 => '44',
(int) 1 => '3',
(int) 2 => '32',
(int) 3 => '23',
(int) 4 => '12',
(int) 5 => '32'
)
)
虽然我希望它看起来像这样
array(
(int) 0 => array(
(int) 0 => '1',
(int) 1 => '2',
(int) 2 => '3',
(int) 3 => '4',
(int) 4 => '5',
(int) 5 => '6',
(int) 6 => '7',
(int) 7 => '8'
(int) 8 => '44',
(int) 9 => '3',
(int) 10 => '32',
(int) 11 => '23',
(int) 12 => '12',
(int) 13 => '32'
)
)
答案 0 :(得分:2)
嗯,从我的观点来看,你只是把它弄错了。使foreach遍历逗号分隔列表并手动添加它而不是推送整个数组。
$sales=array();
foreach ($sales_detailed as $sale_detailed) {
$sale_detailed_ids = explode( ',', $sale_detailed['Sale']['product_ids'] );
foreach($sale_detailed_ids as $ids) {
$sales[] = $ids;
}
}
答案 1 :(得分:1)
您必须将一些自定义代码写入"跳过"第一级数组,只合并第二级。
function mergeKeepIds($a, $b) {
$keys = array_unique(array_keys($a) + array_keys($b)); // Grab all the keys.
$result = [];
foreach ($keys as $key) {
$valueA = array_key_exists($key, $a) ? $a[$key] : [];
$valueB = array_key_exists($key, $b) ? $b[$key] : [];
$result[$key] = array_merge($valueA, $valueB);
}
return $result;
}