php 将两个数组组合成第三个数组,其中一个数组的键是不恒定的

62lalag4  于 2023-03-28  发布在  PHP
关注(0)|答案(3)|浏览(172)

我有两个数组如下。

$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
);

规则是break anytime $key=99。目前,我尝试使用array_chunk,但语法只允许我按唯一键的数量对数组进行分块,在我的示例中,这不是常数。有什么建议吗?

crcmnpdw

crcmnpdw1#

您需要编写一个自定义脚本,根据您的逻辑组合这两个数组。
您需要从$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);
tjvv9vkg

tjvv9vkg2#

可以使用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);

DEMO

ffvjumwh

ffvjumwh3#

不是有条件地递增计数器来确定数据被推入数组的位置,而是可以通过将引用推入结果数组来填充行数据。
代码:(Demo

$result = [];
foreach ($keys as $i => $k) {
    if (!isset($ref)) {
        $result[] = &$ref;
    }
    $ref[$k] = $values[$i];
    if ($k == 99) {
        unset($ref);
    }
}

var_export($result);

如果你想维护一个计数器变量,它可以看起来像这样:(Demo

$counter = 0;
$result = [];
foreach ($keys as $i => $k) {
    $result[$counter][$k] = $values[$i];
    if ($k == 99) {
        ++$counter;
    }
}

var_export($result);

相关问题