PHP从各个stdClass对象的数组中的关联数组中获取/检查值

问题描述 投票:0回答:1

对此有真正的问题。我希望能够从通过API返回的数据中获取值。

即获得价值

$CM_user_customfields['Organisation'],   
$CM_user_customfields->Organisation.

甚至可能吗?我已经尝试过循环并重建阵列,但我总是得到类似的结果,也许是过度思考它。

我无法使用[int] =>,因为自定义字段的数量会发生很大变化。

$CM_user_customfields =  $CM_details->response->CustomFields ;
echo '<pre>' . print_r( $CM_user_customfields, true ) . '</pre>';

// returns
Array
(
    [0] => stdClass Object
        (
            [Key] => Job Title
            [Value] => Designer / developer
        )

    [1] => stdClass Object
        (
            [Key] => Organisation
            [Value] => Jynk
        )

    [2] => stdClass Object
        (
            [Key] => liasoncontact
            [Value] => Yes
        )

    [3] => stdClass Object
...

非常感谢,D。

php arrays stdclass
1个回答
3
投票

我建议先转换为关联数组:

foreach($CM_user_customfields as $e) {
    $arr[$e->Key] = $e->Value;
}

现在您可以访问它:

echo $arr['Organisation'];

你也可以通过以下方式实现它:(PHP 7可以转换stdClass并且可以做到这一点)

$arr = array_combine(array_column($CM_user_customfields, "Key"), array_column($CM_user_customfields, "Value")));
© www.soinside.com 2019 - 2024. All rights reserved.