我有以下数组:
Array (
[0] => Array ( [id] => 1 [grpname] => RF [grpid] => 1 [value] => 1.40 )
[1] => Array ( [id] => 1 [grpname] => BP [grpid] => 2 [value] => 1.90 )
[2] => Array ( [id] => 1 [grpname] => DSH [grpid] => 3 [value] => 2.46 )
[3] => Array ( [id] => 2 [grpname] => RF [grpid] => 1 [value] => 1.40 )
[4] => Array ( [id] => 2 [grpname] => BP [grpid] => 2 [value] => 1.90 )
[5] => Array ( [id] => 2 [grpname] => DSH [grpid] => 3 [value] => 2.46 )
[6] => Array ( [id] => 3 [grpname] => RF [grpid] => 1 [value] => 1.40 )
[7] => Array ( [id] => 3 [grpname] => BP [grpid] => 2 [value] => 1.90 )
[8] => Array ( [id] => 3 [grpname] => DSH [grpid] => 3 [value] => 2.46 )
)
如何根据id键拆分它并为每个id创建一个数组?
最诚挚的问候 Artam
答案 0 :(得分:0)
这将是你问题的答案......
<?php
$payload = Array (
[0] => Array ( [id] => 1 [grpname] => RF [grpid] => 1 [value] => 1.40 )
[1] => Array ( [id] => 1 [grpname] => BP [grpid] => 2 [value] => 1.90 )
[2] => Array ( [id] => 1 [grpname] => DSH [grpid] => 3 [value] => 2.46 )
[3] => Array ( [id] => 2 [grpname] => RF [grpid] => 1 [value] => 1.40 )
[4] => Array ( [id] => 2 [grpname] => BP [grpid] => 2 [value] => 1.90 )
[5] => Array ( [id] => 2 [grpname] => DSH [grpid] => 3 [value] => 2.46 )
[6] => Array ( [id] => 3 [grpname] => RF [grpid] => 1 [value] => 1.40 )
[7] => Array ( [id] => 3 [grpname] => BP [grpid] => 2 [value] => 1.90 )
[8] => Array ( [id] => 3 [grpname] => DSH [grpid] => 3 [value] => 2.46 )
)
// creates "separate" variables for entries named $payload_0, $payload_1, ...
foreach ($payload as $key=>$value) {
$innerName = sprintf('payload_%s', $key);
$$innerName = $value;
}
// test output to make the conversion clear:
var_dump($payload_4);
......这没什么意义。
这只会使事情变得更复杂,并使内存使用量翻倍。您也可以直接使用内部数组作为$payload[4]
。
所以问题是:为什么你想做这样的事情?出于什么目的?
旁注:上面的代码不起作用,因为我刚刚复制了指定的数组符号,这是无效的PHP代码。但你应该明白......
考虑到下面的评论,我说这更有可能是你想要的:
<?php
$payload = Array (
[0] => Array ( [id] => 1 [grpname] => RF [grpid] => 1 [value] => 1.40 )
[1] => Array ( [id] => 1 [grpname] => BP [grpid] => 2 [value] => 1.90 )
[2] => Array ( [id] => 1 [grpname] => DSH [grpid] => 3 [value] => 2.46 )
[3] => Array ( [id] => 2 [grpname] => RF [grpid] => 1 [value] => 1.40 )
[4] => Array ( [id] => 2 [grpname] => BP [grpid] => 2 [value] => 1.90 )
[5] => Array ( [id] => 2 [grpname] => DSH [grpid] => 3 [value] => 2.46 )
[6] => Array ( [id] => 3 [grpname] => RF [grpid] => 1 [value] => 1.40 )
[7] => Array ( [id] => 3 [grpname] => BP [grpid] => 2 [value] => 1.90 )
[8] => Array ( [id] => 3 [grpname] => DSH [grpid] => 3 [value] => 2.46 )
)
// iterate over the payload array and do whatever you want to do with the entries:
foreach ($payload as $key=>$value) {
// here output the inner array however you want to
// $value now _is_ the inner value in each iteration of the loop
}