DobotJr DobotJr - 6 months ago 14
PHP Question

Create multidimensional array PHP

I need help creating an array within an array using this data. This data is already in an array like this:

[0] => META>>DisplayName=Donald Trump
[1] => META>>EmailAddress=TheDon@rnc.com
[2] => META>>EmployeeID=E13342
[3] => CLOUD>>DisplayName=Hillary Clinton
[4] => CLOUD>>EmailAddress=Hill@dnc.com
[5] => CLOUD>>EmployeeID=E13423
[6] => AD>>DisplayName=Bernie Sanders
[7] => AD>>EmailAddress=Bernie@dnc.com
[8] => AD>>EmployeeID=E121233


I'm trying to turn it into something like this:

array(
[meta] => Array
(
[DisplayName]=>Donald Trump
[EmailAddress]=>TheDonald@rnc.com
[EmployeeID]=>E666420
[EmployeeType]=>E
)
)


What I have so far but it's not working:

$properties = array("DisplayName",
"EmailAddress",
"EmployeeID",
"EmployeeType")

$data = array();
foreach($output as $line) {
$sep = explode(">>",$line);
$data[$sep[0]] = array();
for ($x=0;$x<count($properties);$x++) {
$split = explode("=",$sep[1]);
$data[$sep[0]][$p] = $split[1];
}

}

Answer

This can be achieve like this:

$output = [
 'META>>DisplayName=Donald Trump',
 'META>>EmailAddress=TheDonald@rnc.com',
 'META>>EmployeeID=E666420',
 'META>>EmployeeType=E',
];

$result = array();

foreach ($output as $value) {
  $meta = explode('>>', $value);
  $property = explode('=', $meta[1]);
  $result['meta'][$property[0]] = $property[1]; 
}

var_dump($result);

http://ideone.com/Twq9gr