将stdClass对象转换为多维数组

时间:2014-01-13 06:10:42

标签: php arrays

我有$positions stdClass对象,如下所示

Array
(
    [0] => stdClass Object
        (
            [id] => 2
            [position] => am
            [label] => Account Manager
        )

    [1] => stdClass Object
        (
            [id] => 6
            [position] => agn
            [label] => Agent
        )

    [2] => stdClass Object
        (
            [id] => 5
            [position] => bdev
            [label] => Business Development
        )

    [3] => stdClass Object
        (
            [id] => 4
            [position] => fin
            [label] => Finance
        )

    [4] => stdClass Object
        (
            [id] => 1
            [position] => hr
            [label] => Human Resource
        )

    [5] => stdClass Object
        (
            [id] => 3
            [position] => it
            [label] => Information Technology
        )

)

我想将其转换为多维数组,因此我需要return it into a function并根据需要重复使用..如下所示

array(

    array (
        'id' => 1,
        'position' => 'admin',
        'label' => 'Administrator'
    ),

    array (
        'id' => 2,
        'position' => 'am',
        'label' => 'Account Manager'
    ),

    array (
        'id' => 3,
        'position' => 'hr',
        'label' => 'Human Resource'
    ),
);

我不确定数组的形式到底是什么,但我想返回数组,这样我就可以获得整个表格,而不是将它用于系统。

我在下面尝试过,但它没有提供我想要的输出

foreach($positions as $position){
    $array[] = $position->id;
    $array[] = $position->label;
    $array[] = $position->position;
}

echo '<pre>',print_r($array),'</pre>';

输出

Array
(
    [0] => 2
    [1] => Account Manager
    [2] => am
    [3] => 6
    [4] => Agent
    [5] => agn
    [6] => 5
    [7] => Business Development
    [8] => bdev
    [9] => 4
    [10] => Finance
    [11] => fin
    [12] => 1
    [13] => Human Resource
    [14] => hr
    [15] => 3
    [16] => Information Technology
    [17] => it
)

这是显而易见的输出,但我需要知道如何获得返回多维数组。

3 个答案:

答案 0 :(得分:2)

您的结果是平面数组,因为您是通过[]将元素添加到数组中的。要解决此问题,请将元素作为数组添加到主数组中,例如:

foreach($positions as $position)
{
    $array[] = [
       'id'      => $position->id,
       'label'   => $position->label,
       'position'=> $position->position
    ];
}

在PHP&lt; 5.4中,不可能使用[]进行数组定义,因此请改用array()

答案 1 :(得分:1)

您可以使用get_object_vars():

$array = array();
foreach($positions as $pos){
  $array[] = get_object_vars($pos);
}

See it in action

注意变量的可访问性级别:

 Gets the accessible non-static properties of the given object according to scope. 

答案 2 :(得分:0)

要在我的项目中处理这类事情,我只是输入它:

$positions_array = (array)$positions;

这将保留现有结构,但将其转换为数组。