简体   繁体   English

基于字符串的开头组合 PHP 数组值

[英]Combining PHP array values based on the start of a string

I have a multidimensional PHP array looking like that:我有一个看起来像这样的多维 PHP 数组:

[14]=>
  array(2) {
    [0]=>
    int(29)
    [1]=>
    int(129)
  }

[193]=>
  array(3) {
    [0]=>
    int(6009231)
    [1]=>
    int(6324415)
    [2]=>
    int(5682922)
  }

EDIT: there can be more than 2 keys (here 14 and 193).编辑:可以有超过 2 个键(这里是 14 和 193)。 There can be n keys.可以有 n 个键。

My goal is to get the following strings in a new array:我的目标是在新数组中获取以下字符串:

14:29;193:6009231
14:29;193:6324415
14:29;193:5682922
14:129;193:6009231
14:129;193:6324415
14:129;193:5682922

The conditions are that the key, values are separated by : and the elements are separated by ;条件是键、值之间用:分隔,元素用;分隔。 The first element should always be the first key (14) then we go through the values of this first key.第一个元素应该始终是第一个键(14)然后我们通过这个第一个键的值 go。 The second element is always the second key, and again we go through the values of the second element.第二个元素始终是第二个键,我们再次通过第二个元素的值 go。 EDIT: the keys are always sorted ascending编辑:键总是按升序排序

I manage to get all possible combinations key:values in the desired format as follow:我设法以所需格式获得所有可能的组合键:值,如下所示:

$properties_values_combinations = []
foreach ($myarray as $property) {
    foreach ($property as $value) {
        $properties_values_combinations[] = (string)$property.":".(string)$value;
    }
}

However how can I combine elements of this array according to the result I want to achieve?但是如何根据我想要达到的结果组合这个数组的元素呢?

You can extract the keys of the array using array_keys and then iterate over each of the subarrays using those keys:您可以使用array_keys提取数组的键,然后使用这些键迭代每个子数组:

$result = array();
list($k1, $k2) = array_keys($myArray);
foreach ($myArray[$k1] as $v1) {
    foreach ($myArray[$k2] as $v2) {
        $result[] = "$k1:$v1;$k2:$v2";
    }
}
print_r($result);

Output: Output:

Array
(
    [0] => 14:29;193:6009231
    [1] => 14:29;193:6324415
    [2] => 14:29;193:5682922
    [3] => 14:129;193:6009231
    [4] => 14:129;193:6324415
    [5] => 14:129;193:5682922
)

Demo on 3v4l.org 3v4l.org 上的演示

Update更新

If there can be more than 2 sub arrays, the problem needs to be solved using recursion.如果子 arrays 可以有 2 个以上,则需要使用递归解决问题。 This function will do what you want:这个 function 会做你想做的事:

function list_values($array) {
    $output = array();
    $k1 = array_keys($array)[0];
    if (count($array) == 1) {
        foreach ($array[$k1] as $v1) {
            $output[] = "$k1:$v1";
        }
    }
    else {
        foreach ($array[$k1] as $v1) {
            foreach (list_values(array_slice($array, 1, null, true)) as $k2v2) {
                $output[] = "$k1:$v1;$k2v2";
            }
        }
    }
    return $output;
}

Demo with 4 entry array at 3v4l.org .3v4l.org上带有 4 个入口数组的演示。 Output too long to show here. Output 太长,无法在此处显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM