如何像这样对数组进行分组



我有一个这样的数组:

Array
(
[0] => Array
(
[lvid] => 01-3234
[status] => 0
[totals] => 500
[tgls] => 2020-05-24
)
[1] => Array
(
[lvid] => 01-3234
[status] => 1
[totals] => 100,100
[tgls] => 2020-05-24,2020-05-25
)    
)

我希望结果是这样的:

Array
(
[0] => Array
(
[01-3234] => Array
(
[0] => Array
(
[2020-05-24] => 500
)
[1] => Array
(
[2020-05-24] => 100
[2020-05-25] => 100
)
)             
)
)

有人帮助我,请

利用分解array_combine函数

akshay@ideapad:~$ cat test.php 
<?php
$input = array(
array( "lvid" => "01-3234", "status" => 0, "totals" => 500, "tgls" => "2020-05-24" ),
array( "lvid" => "01-3234", "status" => 1, "totals" => "100,100", "tgls" => "2020-05-24,2020-05-25"  )
);
// your given input samples
print_r($input);
// process and create new array
$out=array();
foreach($input as $item)
{
$toadd = array_combine(
explode(",",$item["tgls"]),
explode(",", $item["totals"])
);
if(isset($out[$item['lvid']]))
{
$out[$item['lvid']][] = $toadd;            
}else
{ 
$out[$item['lvid']] = array($toadd);
} 
}
// finally expected output
print_r(array($out));

测试于:

akshay@ideapad:~$ php --version
PHP 7.4.6 (cli) (built: May 14 2020 10:02:44) ( NTS )

输出:

akshay@ideapad:~$ php test.php 
Array
(
[0] => Array
(
[lvid] => 01-3234
[status] => 0
[totals] => 500
[tgls] => 2020-05-24
)
[1] => Array
(
[lvid] => 01-3234
[status] => 1
[totals] => 100,100
[tgls] => 2020-05-24,2020-05-25
)
)
Array
(
[0] => Array
(
[01-3234] => Array
(
[0] => Array
(
[2020-05-24] => 500
)
[1] => Array
(
[2020-05-24] => 100
[2020-05-25] => 100
)
)
)
)

相关内容

  • 没有找到相关文章

最新更新