如何将php数组与对象转换为简单数组?

时间:2012-07-11 10:26:49

标签: php drupal

我有一个返回像这样的数组的函数

Array
(
    [0] => stdClass Object
        (
            [tid] => 1
            [vid] => 2
            [name] => About Us
            [description] => 
            [format] => wysiwyg_editor
            [weight] => 0
            [depth] => 0
            [parents] => Array
                (
                    [0] => 0
                )

        )

[1] => stdClass Object
    (
        [tid] => 200
        [vid] => 2
        [name] => Stories
        [description] => 
        [format] => wysiwyg_editor
        [weight] => 0
        [depth] => 0
        [parents] => Array
            (
                [0] => 0
            )

    )

为简化它以供进一步使用,我想将此数组转换为简单的数组,其键为[tid],值为[name] 所以它会像这样:

Array
(
    [1] => About Us
    [200] => Stories

任何有关正确代码语法的提示或帮助都会很棒。谢谢

2 个答案:

答案 0 :(得分:2)

试试这个:

$result = array();
foreach ($data as $row) {
    $result[$row->tid] = $row->name;
}
var_dump($result);

答案 1 :(得分:2)

使用此代码段:

function transform($arr){
   $result = array();

   foreach($arr as $obj){
     $result[$obj->tid] = $obj->name;
   }

   return $result;
}