我有2个数组如下。
$keys = [1,2,3,4-1,99,1,2,3,4-1,4-2,4-3,99,1,2,3,4-1,4-2,99]
$values = [a,b,c,d,x,a1,b1,c1,d1,e,g,x,a2,b2,c2,d2,e,x]
我想组合成一个像:
这样的数组$result = array(
[0]=>array(1=>a,2=>b,3=>c,4-1=>d,99=>x),
[1]=>array(1=>a1,2=>b1,3=>c1,4-1=>d1,4-2=>e,4-3=>g,99=>x),
[2]=>array(1=>a2,2=>b2,3=>c2,4-1=>d2,4-2=>e,99=>x
);
规则随时中断$ key = 99。 目前,我尝试使用array_chunk但语法只允许我通过唯一键的数量来对数组进行分块,这在我的示例中不是常量。 有什么建议吗?
答案 0 :(得分:1)
您需要编写一个自定义脚本,它根据您的逻辑组合这两个数组。
您需要从$keys
数组中获取每个键,并将其与$values
数组中的相同元素按位置组合。
示例:
<?php
$keys = ['1', '2', '3', '4-1', '99', '1', '2', '3', '4-1', '4-2', '4-3', '99', '1', '2', '3', '4-1', '4-2', '99'];
$values = ['a', 'b', 'c', 'd', 'x', 'a1', 'b1', 'c1', 'd1', 'e', 'g', 'x', 'a2', 'b2', 'c2', 'd2', 'e', 'x'];
$i = 0;
$result = [];
foreach ($keys as $index => $key) {
if (empty($result[$i]))
$result[$i] = [$key => $values[$index]];
else
$result[$i][$key] = $values[$index];
if ($key == 99)
++$i;
}
print_r($result);
答案 1 :(得分:0)
您可以使用foreach循环来实现此目的
$keys = ["1","2","3","4-1","99","1","2","3","4-1","4-2","4-3","99","1","2","3","4-1","4-2","99"];
$values = ["a","b","c","d","x","a1","b1","c1","d1","e","g","x","a2","b2","c2","d2","e","x"];
$new_array = array();
$split_at = "99";
$i = 0;
foreach ($keys as $key => $value) {
$new_array[$i][$value] =$values[$key];
if($split_at == $value){
$i++;
}
}
print_r($new_array);