我想做:
生成的数组:
array
'first_name' => string 'sushil' (length=6)
'last_name' => string 'asfasfaf' (length=8)
'gen' => string 'Male' (length=4)
'language' => string 'PHP' (length=3)
'biodata' => string 'sfsafsaf hdffd ' (length=15)
'hobbies' =>
array
0 => string 'gaming' (length=6)
1 => string 'football' (length=8)
2 => string 'cricket' (length=7)
'academic_qualification' => string 'Bachelor' (length=8)我想按照上面的步骤修改:
//finds if child array exists. If exists interchange key and value and update value to '1'.
array
'gaming' => int 1
'football' => int 1
'cricket' => int 1最后,取消原始子数组,并将修改后的子数组的元素合并到父数组。我的预期数组表单:
array
'first_name' => string 'sushil' (length=6)
'last_name' => string 'asfasfaf' (length=8)
'gen' => string 'Male' (length=4)
'language' => string 'PHP' (length=3)
'biodata' => string 'sfsafsaf hdffd ' (length=15)
'academic_qualification' => string 'Bachelor' (length=8)
'gaming' => int 1
'football' => int 1
'cricket' => int 1我试过这样做,但不起作用:
$submited_data = $_POST;
var_dump($submited_data);
foreach($submited_data as $value){
if(is_array($value)) { //checks if array contains array.
$a = array_flip($value); //then interchange
var_dump($a);
foreach($a as $key=>$b){
$a[$key] = 1; //update all value to '1'.
}
array_push($submited_data,$a); // here is the problem I cannot proceed to furthur step. Please help me. How to merge modified child array to parent array.
var_dump($a);
}
}谢谢。
发布于 2015-07-13 11:30:44
我刚刚重写了你的代码。如果出了什么问题,请告诉我!
<?php
$submited_data = $_POST;
foreach($submited_data as $key => $data)
{
if(is_array($data))
{
foreach($data as $sub_data)
{
$submited_data[$sub_data] = 1;
}
unset($submitted_data[$key]);
}
}发布于 2015-07-13 11:31:22
假设$array是带有子数组的数组,
$mergedArray = [];
array_walk_recursive($array, function($a,$b) use (&$mergedArray) { $mergedArray[$b] = $a; });
echo '<pre>';
print_r($mergedArray);
echo '</pre>';https://stackoverflow.com/questions/31382086
复制相似问题