从PHP中的对象数组获取特定数据

时间:2019-07-03 11:24:17

标签: php object

我只想从对象内部的数组中获取特定数据。

当我运行此代码时:

$response = $client->__call('get', $request);
$vars = get_object_vars($response); 
print_r($vars);

它给了我整个阵列。

Array
(
  [clients] => Array
    (
      [0] => stdClass Object
        (
          [id] => 2
          [guests] => Array
            (
              [0] => stdClass Object
                (
                  [id] => 2
                  [firstName] => Greg
                  [lastName] => Gregson
                )
            )
          [invoiceData] => stdClass Object
            (
              [taxNumber] => 12345678
            )
        )
      [1] => stdClass Object
        (
          [id] => 3
          [guests] => Array
            (
              [0] => stdClass Object
                (
                  [id] => 3
                  [firstName] => Paul
                  [lastName] => Paulson
                )
            )
          [invoiceData] => stdClass Object
            (
              [taxNumber] => 34567891
            )
        )
      [2] => stdClass Object
        (
          [id] => 4
          [guests] => Array
            (
              [0] => stdClass Object
                (
                  [id] => 4
                  [firstName] => John
                  [lastName] => Johnson
                )
            )
          [invoiceData] => stdClass Object
            (
              [taxNumber] => 23456789
            )
        )
    )
)

我只希望将[id][firstName][taxNumber]视为一个数组,如下所示:

2, Greg, 12345678
3, Paul, 34567891
4, John, 23456789

这可能吗?我该怎么办?

1 个答案:

答案 0 :(得分:0)

您可以使用array_walk()仅抓取预期的物品。一个例子:

array_walk($vars['clients'], function (&$item) {
    $item = ["{$item->id}, {$item->guests[0]->firstName}, {$item->invoiceData->taxNumber}"];
});