从php中的数组中获取值

时间:2015-03-20 21:34:47

标签: php arrays object

我的代码中有以下内容:

stdClass Object ( [orders] => Array ( [0] => stdClass Object ( [shipping_address] => stdClass Object ( [first_name] => John [last_name] => Doe [company] => [address_1] => 3927 Walnut Grove [address_2] => [city] => Rosemead [state] => CA [postcode] => 90001 [country] => US ) ) [1] => stdClass Object ( [shipping_address] => stdClass Object ( [first_name] => chris [last_name] => koh [company] => [address_1] => 745 bow [address_2] => [city] => diamond [state] => CA [postcode] => 90015[country] => US ) ) ) )

我如何从两个元素中仅提取first_name?

约翰和克里斯

1 个答案:

答案 0 :(得分:1)

你得到的“数组”是数组和对象的混合,对象的访问方式不同。

数组值由

访问
$an_array = array('apple','banana');
$an_array[0]; //will return apple

通过

访问对象值区域
$an_object->key;

看一下你的回归对象

stdClass Object ( //<-- Object
  [orders] => Array ( //<-- Array
    [0] => stdClass Object (  //<-- Object
      [shipping_address] => stdClass Object ( //<-- Object
        [first_name] => John 
 etc..

因此,例如,您可以使用以下命令访问它:

$arrayAndObjects->orders[0]->shipping_address->first_name

希望这有助于您理解它,这里有链接到Arrays&amp;的php文档。对象

http://php.net/manual/en/language.types.object.php http://php.net/manual/en/language.types.array.php