【问题标题】:How to get value from object in php如何从php中的对象获取值
【发布时间】:2020-05-28 06:27:39
【问题描述】:

我需要从所有这些对象类中获取[text] 的值。

我可以从数组中获取值但是从数组中的这些类对象中,我无法获取[text] 的值。

任何帮助将不胜感激。

Array
(
 [0] => stdClass Object
 (
    [text] => time
    [tr] => Array
    (
        [0] => stdClass Object
        (
            [text] => while
            [syn] => Array
            (
                [0] => stdClass Object
                (
                    [text] => when
                )
            )
        )
        [1] => stdClass Object
        (
            [text] => occasion  
            [syn] => Array
            (
                [0] => stdClass Object
                (
                    [text] => moment
                )
                [1] => stdClass Object
                    (
                        [text] => day   
                    )
                    [2] => stdClass Object
                        (
                            [text] => date  
                        )
                )
            )
        )
    )
)

【问题讨论】:

  • 请发布您尝试过的预期结果+代码............
  • array[0]->text 是你所需要的
  • 这实际上是一个基于 api 的结果,所以代码很大。我使用 json decode 输出这个结果 var_dump( json_decode($myArray));然后我使用了 print_r($myArray->response; 但它给出了我上面的结果。虽然我想要第一个数组 [text] => time 中的“text”值,但我想要所有的“text”值。
  • @hlfrmn 还有$array[0]->tr[0]->text$array[0]->tr[1]->text, $array[0]->tr[0]->syn[0]->text`,等等。
  • 要获得所有这些,您可能需要编写一个递归函数。

标签: php arrays object


【解决方案1】:

这不是最优雅的解决方案,但这样的解决方案应该可以解决问题:

<?php
$data = [
    [
        'text' => 'time',
        'tr' => [
            'text' => 'while',
            'syn' => [
                'text' => 'when'
            ],
            [
                'text' => 'occasion',
                'syn' => [
                    [
                        'text' => 'moment'
                    ],
                    [
                        'text' => 'day'
                    ],
                    [
                        'text' => 'date'
                    ]
                ]
            ]
        ]
    ]
];

$data = json_decode(json_encode($data));

function recurseProperties($object) {
    $text = [];
    foreach ($object as $property => $value) {
        if ($property === 'text') {
            echo $property . '  =>  ' . $value . "\n";
            $text[] = $value;
        } else {
            $text = array_merge($text, recurseProperties($value));
        }
    }
    return $text;
}

function extractText($data) {
    $text = [];
    foreach ($data as $object) {
        $text = array_merge($text, recurseProperties($object));
    }

    return $text;
}

var_dump(extractText($data));

或者,如果您习惯使用数组并且它是 json 源,您可以这样做:

  json_decode($jsonString, true)

这会将其转换为关联数组,请参阅:https://www.php.net/manual/en/function.json-decode.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 2016-05-14
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多