我有像这样的关联数组
$arrz1=Array([sss] => Array
(
[0] => 315
[1] => 330
[2] => 345
[3] => 315
[4] => 330
[5] => 345
[6] => 360
[7] => 315
[8] => 330
[9] => 345
[10] => 360
[11] => 375
)
[fff] => Array
(
[0] => 315
[1] => 330
[2] => 345
[3] => 315
[4] => 330
[5] => 345
[6] => 360
[7] => 315
[8] => 330
[9] => 345
[10] => 360
[11] => 375
[12] => 750
[13] => 765
[14] => 780
)
)
我想实现这一点。提供的数组大小可以变化,每个下一个不应该有前一个所有元素:
Array([0] => Array
(
[0] => Array
(
[0] => 315
[1] => 330
[2] => 345
[3] => 315
[4] => 330
[5] => 345
[6] => 360
[7] => 315
[8] => 330
[9] => 345
[10] => 360
[11] => 375
)
)
[1] => Array
(
[0] => Array
(
[0] => 750
[1] => 765
[2] => 780
)
)
需要找出最佳时间复杂度最可行的解决方案。所以,获取的结果足够快,可以在相应的截止日期内达到结果。到目前为止,我已经尝试过以下
$array_key = array();
$array_val = array();
$mult = array();
foreach ($arrz1 as $key => $val) {
$diff = array();
foreach($val as $val1)
{
if(!in_array($val1, $array_val))
{
$diff[] = $val1;
}
}
if(!in_array($key, $array_key))
{
$array_key[] = $key;
//print_r($diff);
if(!empty($diff))
{
$mult[] = array($diff);
foreach($val as $value)
{
$array_val[] = $value;
}
}
else
{
$mult[] = array($val);
foreach($val as $value)
{
$array_val[] = $value;
}
}
}
}
结果是正确的,但时间过长
答案 0 :(得分:3)
使用array_diff
和array_values
函数考虑以下方法:
// $arr is your initial array
$items = array_values($arr);
foreach ($items as $k => &$item) {
if ($k != 0) $item = array_values(array_diff($item, $items[$k-1]));
}
print_r($items);
输出:
Array
(
[0] => Array
(
[0] => 315
[1] => 330
[2] => 345
[3] => 315
[4] => 330
[5] => 345
[6] => 360
[7] => 315
[8] => 330
[9] => 345
[10] => 360
[11] => 375
)
[1] => Array
(
[0] => 750
[1] => 765
[2] => 780
)
)
答案 1 :(得分:0)
因此,更快捷的方法是使用array_diff。您可以保持包含已索引元素的当前状态,并继续将新数组与状态进行比较。
这样做很快,很容易理解。
<?php
$arr =
[
'sss' => [315, 330, 345, 125],
'fff' => [315, 330, 345, 125, 750, 756, 780],
'eee' => [330, 345, 220, 750]
];
$state = [];
foreach($arr as $key => $item)
{
$arr[$key] = array_diff($item, $state);
$state += $arr[$key];
}
var_dump($arr);
这将导致:
array(3) {
'sss' =>
array(4) {
[0] =>
int(315)
[1] =>
int(330)
[2] =>
int(345)
[3] =>
int(125)
}
'fff' =>
array(3) {
[4] =>
int(750)
[5] =>
int(756)
[6] =>
int(780)
}
'eee' =>
array(1) {
[2] =>
int(220)
}
}
节点:如果已添加项目eee
以显示元素内的项目顺序无关紧要。