检查数组是否包含子数组并在父数组中合并

时间:2015-07-13 11:24:25

标签: php arrays

我想这样做:

  1. 检查数组是否包含数组。
  2. 如果父数组包含子数组,则交换子数组的键和值。
  3. 将子数组的所有键更新为' 1'。即交换密钥和值后的子数组的值
  4. 删除子数组并将其元素合并到父数组。

    示例:

  5. 生成的数组:

     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);
    
                }
            }
    

    谢谢。

2 个答案:

答案 0 :(得分:1)

我刚刚重写了你的代码。如果出现任何问题请告诉我!

<?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]);
        }
    }

答案 1 :(得分:0)

假设$array是包含子数组的数组,

$mergedArray = [];

array_walk_recursive($array, function($a,$b) use (&$mergedArray) { $mergedArray[$b] = $a; }); 

echo '<pre>';
print_r($mergedArray);