这似乎是一个相当微不足道的问题,请原谅我的无知。仍然掌握数组操作......
我有一个CakePHP应用程序,它将一个数组发布到我的控制器以进行保存。我需要以某种方式重新格式化已发送的数组,以便可以通过Cake的保存行为正确处理它。
发布的数组是:
Array (
[788] => Array ( [id] => 788 )
[787] => Array ( [id] => 787 )
[786] => Array ( [id] => 0 )
[785] => Array ( [id] => 0 )
[value_1] => 0
[analysed_date] => Array (
[month] => 08
[day] => 16
[year] => 2011
)
[job_id] => 34
)
所需数组:
Array (
[0] => Array (
[id] => 788
[value_1] => 0
[analysed_date] => Array (
[month] => 08
[day] => 16
[year] => 2011
)
)
[1] => Array (
[id] => 787
[value_1] => 0
[analysed_date] => Array (
[month] => 08
[day] => 16
[year] => 2011
)
)
)
感谢您花时间去看。
修改
我刚刚意识到我省略了如果数组有[id] =>的事实0它需要被忽略。这是我的主要绊脚石。道歉。我希望编辑能更好地澄清我的问题。
解决
谢谢你的帮助。我能够自己想出解决方案。这就是我想出来的。
foreach($org_array as $key => $value){
if(is_array($value)){
if(isset($value['id'])){
if($value['id'] != 0) {
$data[$i] = array(
'id' => $value['id'],
'value_1'=> $value_1,
'analysed_date' => $date
);
$i++;
}
}
}
}
答案 0 :(得分:1)
这样的事情应该有用,但仅限于你的例子:
$array_keys = array_keys($org_array);
$new_array = array();
foreach ($array_keys as $key)
{
if (is_int($key))
{
$new_array[] = array(
"id" => $key,
"value1" => $org_array["value1"],
"analysed_date" => $org_array["analysed_date"]
);
// you might want to loop throught the original array to get all non-integer key values instead of hard-coding it
}
}
答案 1 :(得分:1)
$main = Array (
[788] => Array ( [id] => 788 )
[787] => Array ( [id] => 787 )
[786] => Array ( [id] => 786 )
[785] => Array ( [id] => 785 )
[value_1] => 0
[analysed_date] => Array (
[month] => 08
[day] => 16
[year] => 2011
)
[job_id] => 34
)
$analysed_date = $main['analysed_date'];
$value1 = $main['value_1'];
$result = array();
$i=0;
foreach($main as $key=>$value)
{
if( is_numeric($key)
{
$result[$i]=array();
$result[$i]['id']=$key;
$result[$i]['value_1']=$value1;
$result[$i]['analysed_date']=$analysed_date;
$i++;
}
}