[英]Merging arrays with different dimensions in PHP
I have 2 different arrays with different dimensions that i need to merge in order to get a result with a specific this structure: 我需要合并具有不同维度的2个不同数组,以获得具有特定结构的结果:
the first: 首先:
Array
(
[0] => Array
(
[0] => 2017-11-03
[1] => 2017-11-05
[2] => 1
)
[1] => Array
(
[0] => 2017-11-23
[1] => 2017-11-25
[2] => 1
)
)
The second: 第二:
Array
(
[0] => 2017-12-26
[1] => 2018-01-30
)
The result should be : 结果应为:
Array
(
[0] => Array
(
[0] => 2017-11-03
[1] => 2017-11-05
[2] => 1
)
[1] => Array
(
[0] => 2017-11-23
[1] => 2017-11-25
[2] => 1
)
[2] => Array
(
[0] =>2017-12-26
[1] => 2018-01-30
[2] => 1
)
)
I tried using array_merge but it does not work because they have not the same dimension. 我尝试使用array_merge,但由于它们的尺寸不相同,因此无法正常工作。 Also I need an element in the second tab ([2] => 1).
另外,我在第二个标签中需要一个元素([2] => 1)。
What you describe is appending, not merging. 您所描述的是附加而不是合并。 Try this:
尝试这个:
$arraySecond[] = 1; // This adds [2]=> 1
$arrayFirst[] = $arraySecond; // This adds second array to end of first
for your given example: 对于您的示例:
$x = ... // first array [2 dimensions]
$y = ... // second array [1 dimension]
$y = array_merge($y, array_diff($x[0], $y)); // add missing '1' to $y or any other key that are present in elements of $x and have to be added to $y
$x[] = $y; // append the 1-dim array as the new element in $x
<?php
$array=Array
(
0 => Array
(
0 => '2017-11-03',
1 => '2017-11-05',
2 => '1',
),
1 => Array
(
0=> '2017-11-23',
1 => '2017-11-25',
2 => '1'
),
);
$arraySmall=Array
(
0 => '2017-12-26',
1 => '2018-01-30'
);
array_push($arraySmall, "1");
array_push($array, $arraySmall);
echo'<pre>';
print_r($array);
And the output is : 输出为:
Array
(
[0] => Array
(
[0] => 2017-11-03
[1] => 2017-11-05
[2] => 1
)
[1] => Array
(
[0] => 2017-11-23
[1] => 2017-11-25
[2] => 1
)
[2] => Array
(
[0] => 2017-12-26
[1] => 2018-01-30
[2] => 1
)
)
This way can work even without this line array_push($arraySmall, "1");
即使没有这一行,这种方式也可以工作
array_push($arraySmall, "1");
You can give it a try. 您可以尝试一下。 In order to "merge" you need same size but for "push" you don't.
为了“合并”,您需要相同的大小,但对于“推送”,则不需要。 So if you commend the line i told you the output will look like this:
因此,如果您赞扬我告诉您的那行,输出将如下所示:
Array
(
[0] => Array
(
[0] => 2017-11-03
[1] => 2017-11-05
[2] => 1
)
[1] => Array
(
[0] => 2017-11-23
[1] => 2017-11-25
[2] => 1
)
[2] => Array
(
[0] => 2017-12-26
[1] => 2018-01-30
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.