我想要替换索引数组。示例$ array [x] [y]到$ array [y] [x]

时间:2016-10-30 18:32:24

标签: php arrays

实施例。我有:

Array (

[0] => Array (
[comments_id] => 1 
[comments_text] => blabla1
) 

[1] => Array (
[comments_id] => 2 
[comments_text] => blabla2
) 

)

我想要:

Array (

[comments_id] => Array (
[0] => 1 
[1] => 2 
)

[comments_text] => Array (
[0] => blabla1 
[1] => blabla2

)

简化想要替换 $array[x][y]$array[y][x] 我用PHP写作。

2 个答案:

答案 0 :(得分:2)

你可以这样做

// the final array which will hold your result array
// considering $results contains your previous array
$final_array = array();
foreach($results as $result) {
    $final_array['comments_id'][] = $result['comments_id'];
    $final_array['comments_text'][] = $result['comments_text'];
}

答案 1 :(得分:1)

你可以使用这样的小功能:

function reverse_array($array) {    
    $out = array();
    foreach($array as $item) {
        foreach($item as $key => $value) {
            if(!isset($out[$key]))
                $out[$key] = array();
            array_push($out[$key], $value);
        }
    }

    return $out;
}