构造一个多维数组

时间:2011-07-27 08:43:47

标签: php

我在PHP中使用数组迭代。

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

Array
(
    [1] => stdClass Object
        (
            [id] => 1
            [comments] => Testing the Data
            [stream_context_id] => 5
            [stream_entity_id] => 
            [class_id] => 1
            [parent_id] => 0
            [learnt_count] => 
            [rating_count] => 
            [abused_count] => 
            [created_by] => 1
            [created_datetime] => 
            [stream_context] => comments
            [name] => 
            [upload_path] => 
            [uploadby] => 
            [upload_time] => 
        )

    [2] => stdClass Object
        (
            [id] => 2
            [comments] => Testing the Data
            [stream_context_id] => 5
            [stream_entity_id] => 
            [class_id] => 1
            [parent_id] => 0
            [learnt_count] => 
            [rating_count] => 
            [abused_count] => 
            [created_by] => 1
            [created_datetime] => 
            [stream_context] => comments
            [name] => 
            [upload_path] => 
            [uploadby] => 
            [upload_time] => 
        )

)

这里第一个索引值,即1和2是它们相应数组中提到的id。

我想要相同的多维数组,索引值为0和1,依此类推。即数组的常用格式。

3 个答案:

答案 0 :(得分:7)

不知道这是不是你的意思,但也许......:

$reindexedArray = array_values($yourArray);

如果您还想将stdClass个对象转换为数组,请尝试:

$reindexedAndArrayifiedArray = array_values(array_map(function ($entry) {
    return (array)$entry;
}, $yourArray));

答案 1 :(得分:1)

array_merge()与空白数组一起使用 - 将重新编号数字索引:

$result = array_merge(Array(), $your_array_here) ;

答案 2 :(得分:1)

这看起来像一个多维数组,因为你有一个包含对象的命名数组。

您的阵列目前是:

$a = array('1'=>Object, '2'=>Object);

而不是:

$a = array('1'=>array('id'=>'1', 'comment'=>'some comment'), '2'=>array());
$b = array();
foreach($a as $key=>$val){
    $b[] = $val;
}