PHP - 将多维数组转换为2D数组

时间:2014-05-06 09:32:16

标签: php arrays multidimensional-array

我有一个像这样的多维数组

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

我想将此数组转换为此格式

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

请帮助!!!。

3 个答案:

答案 0 :(得分:7)

仅限一个指数:

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

如果$multArray中有多个索引:

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

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

答案 1 :(得分:2)

试试这个

$array = array(...); // your array data
$formedArray = array();

foreach ( $array as $arr )
{
    foreach ( $arr['user'] as $key => $value )
    {
        $formedArray[$key] = array_push(explode(",",$value));
    }
}

echo "<pre>";
print_r($formedArray);
echo "</pre>";

答案 2 :(得分:1)

我知道,它有点重复,但你也可以这样做:

foreach($array as $users) {
    foreach($users as &$value) { // &value is assigned by reference
        $users['users']["email"] = explode(",", $value['email']);
        $users['users']["username"] = explode(",", $value['username']);
        $users['users']["description"] = explode(",", $value['description']);
    }
}

但在此之后,您需要使用$value。请参阅官方PHP manual documentation,详细了解&符号在此处的作用。

Demo