I have a json array in my Particles controller that looks like this after json_encode, true:
Array
(
[0] => Array
(
[Particle.day_id] => Sat
[Particle.week_no] => 1
[Particle.pattern_id] => 589
[Particle.work] => 0
)
[1] => Array
(
[Particle.day_id] => Fri
[Particle.week_no] => 1
[Particle.pattern_id] => 589
[Particle.work] => 0
)
[2] => Array
(
[Particle.day_id] => Thu
[Particle.week_no] => 1
[Particle.pattern_id] => 589
[Particle.work] => 0
)
[3] => Array
(.....
I am trying to convert this array to the correct format for a multiple record save:
A开发者_运维知识库rray
(
[Particle] => Array(
[0] => Array
(
[day_id] => Sat
[week_no] => 1
[pattern_id] => 589
[work] => 0
)
[1] => Array
(
[day_id] => Fri
[week_no] => 1
[pattern_id] => 589
[work] => 0
)
)
....
Where Particle is my Cakephp model name.
The nearest I can get is using this code (php):
$output = array();
foreach ($jsonData as $keyA => $valueA) {
foreach ($valueA as $keyB => $valueB) {
$output = Set::insert( $output, $keyB, $valueB );
}
}
Where $jsonData is the json_encoded array. This gives me:
Array
(
[Particle] => Array
(
[day_id] => Sun
[week_no] => 1
[pattern_id] => 589
[work] => 1
)
)
Which is only the first part of the array - how do I get the rest of the array?
I know the answer will probably be straighforward but it has baffled me for too long now!
Thanks for any help.
$result = array();
$parentKey = null;
foreach ($jsonData as $keyA => $valueA) {
foreach ($valueA as $keyB => $valueB) {
$keyB = explode('.', $keyB);
list($parentKey, $childKey) = $keyB;
$output[$childKey] = $valueB;
}
if(!isset($result[$parentKey]))
$result[$parentKey] = array();
array_push($result[$parentKey], $output);
}
print_r($result);
Your current code it over writing the array $output. Thats why it is showing you the last part of data.
精彩评论