Tuesday, 28 August 2018

PHP - Convert a multidimensional array to a 2D array


I have an array which is multidimensional like this


array(
    0 => array(
        'User' => array(
                 'email' => 'test@yahoo.com ,testuser@yahoo.com',
                 'username' => 'test,testuser',
                 'description' => 'description1,description2'
                  )
         )
);

I want to convert this array into this form
$User = array(
    'email' => array(
        'test@yahoo.com',
        'testuser@yahoo.com'
    ),
    'username' => array(
        'test',
        'testuser'
    ),
    'description' => array(
        'description1',
        'description2'
    )
);

Please help needed!!!.

For only one index:
$arrayTwoD = array();
foreach ($valueMult[0]['User'] as $key => $value) {
    $arrayTwoD[$key] = array_push(explode(',', $value));
}

If you have multiple indexes in $multArray:
$arrayTwoD = array();
foreach ($multArray as $keyMult => $valueMult) {
    foreach ($valueMult['User'] as $key => $value) {
        $arrayTwoD[$keyMult][$key] = array_push(explode(',', $value));
    }
}

or
$arrayTwoD = array();
foreach ($multArray as $array) {
    foreach ($array['User'] as $key => $value) {
        $arrayTwoD[$key] = array_push(explode(',', $value));
    }
}

0 comments:

Post a Comment