0

A little help needed here I have this array:

0 => array:4 [▼
    "StudentName" => "John Doe "
    "StudentNumber" => "2055222"
    0 => array:1 [▼
      "Test" => 33.5
       ]
    1 => array:1 [▼
      "Assignment" => 57.0
       ]
 ]
1 => array:4 [▼
    "StudentName" => "Jane Doe"
    "StudentNumber" => "5222112"
    0 => array:1 [▼
       "Test" => 47.0
       ]
    1 => array:1 [▼
      "Assignment" => 68.0
   ]
]
2 => array:4 [▼
     "StudentName" => "Alice Doe"
     "StudentNumber" => "5555555"
     0 => array:1 [▼
         "Test" => 0.0
         ]
     1 => array:1 [▼
        "Assignment" => 67.0
    ]
]

And I want to convert it to look like this:

0 => array:4 [▼
"StudentName" => "John Doe "
"StudentNumber" => "20160022"
"Test" => 33.5
"Assignment" => 57.0]

Is there some sort of php function I can use? Edit: Added more examples to help you think of a better solution

Richard Tonata
  • 363
  • 1
  • 6
  • 14

3 Answers3

0

There's no native array flatten in PHP but you can do this:

function array_flatten($array) { 
    if (!is_array($array)) { 
        return false; 
    } 
    $result = array(); 
    foreach ($array as $key => $value) { 
        if (is_array($value)) { 
            $result = array_merge($result, array_flatten($value)); 
        } else { 
            $result[$key] = $value; 
        } 
    } 
    return $result; 
}

Found here

Also numerous other approaches here: How to Flatten a Multidimensional Array?

Community
  • 1
  • 1
OK sure
  • 2,617
  • 16
  • 29
  • That code loses the Associative names ` 0 => "John Doe " 1 => "67/2016" 2 => 33.5 3 => 57.0 ` Plus it flattens the whole array – Richard Tonata Nov 02 '16 at 19:03
0

You can do it using like this (not tested):

$arr = Array();
foreach($oldArr AS $k => $v){
    if(is_array($v)){
        foreach($v AS $a => $b){
            $arr[$a] = $b;
        }
    }else{
        $arr[$k] = $v;
    }
}
Tariq
  • 2,853
  • 3
  • 22
  • 29
0

This should work:

// Store your new array in a separate variable to avoid key conflicts with trying to us unset() in a loop
$new_array = array();

foreach($original_array as $k=>$v)
{
    if(is_array($v)) // check if element is an array
    {
        foreach($v as $k2=>$v2) // loop the sub-array and add its keys/indexes to the new array
        {
            $new_array[$k2] = $v2;
        }
    }
    else
    {
        // the element is not a sub-array so just add the key and value to the new array
        $new_array[$k] = $v;
    }
}
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77