stdClass Object
(
[Id] => 23490
[Receipt] => 7684454
[DateTime] => 2019-04-23T19:17:28.000
[Type] => Consumer
[Transactions] => Array
(
[0] => stdClass Object
(
[PacId] => 90
[Label] => GDHSGSHE562543
[Name] => VHSS - AS-89
[Sold] => 27.9
[Unit] => Grams
[Abbreviation] => g
[Price] => 198
[State] =>
[Date] =>
[LastModified] => 2019-04-23T19:17:29+00:00
)
)
[Final] =>
[Date] =>
[LastModified] => 2019-04-23T19:17:29+00:00
)
我正在使用以下代码,但对我不起作用。我想使用下面的代码访问所有带有值的名称,但对我不起作用。我该怎么解决?
$iterator = new RecursiveArrayIterator($f_data);
while ($iterator->valid()) {
if ($iterator->hasChildren()) {
// print all children
foreach ($iterator->getChildren() as $key => $value) {
echo $key . ' : ' . $value . "\n";
}
} else {
echo "No children.\n";
}
$iterator->next();
}
我想要输出如下
stdClass Object
(
[Id] => 23490
[Receipt] => 7684454
[DateTime] => 2019-04-23T19:17:28.000
[Type] => Consumer
[Transactions] => Array
[PacId] => 90
[Label] => GDHSGSHE562543
[Name] => VHSS - AS-89
[Sold] => 27.9
[Unit] => Grams
[Abbreviation] => g
[Price] => 198
[State] =>
[Date] =>
[LastModified] => 2019-04-23T19:17:29+00:00
[Final] =>
[Date] =>
[LastModified] => 2019-04-23T19:17:29+00:00
)
答案 0 :(得分:0)
$f_data->Transactions
是一个包含对象的数组,因此它将引发该错误:
Recoverable fatal error: Object of class stdClass could not be converted to string
RecursiveIteratorIterator
类更简单的解决方案是也使用RecursiveIteratorIterator
类。
$obj = (your_object_here);
var_dump(flat($obj));
function flat($iterable) {
$arr = [];
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($iterable));
foreach ($iterator as $key => $value) {
$arr[$key] = $value;
}
return (object)$arr;
}
RecursiveArrayIterator
类另一种解决方案可能是具有一个递归函数,当迭代器遇到带有子元素(数组或对象)的元素时,该函数将自行调用。
$obj = (your_object_here);
var_dump(flat($obj));
function flat($iterable) {
$arr = [];
$iterator = (get_class($iterable) === RecursiveArrayIterator::class)
? $iterable
: new RecursiveArrayIterator($iterable);
while($iterator->valid()) {
if ($iterator->hasChildren()) {
$arr = array_merge($arr, (array)flat($iterator->getChildren()));
} else {
$arr[$iterator->key()] = $iterator->current();
}
$iterator->next();
}
return (object)$arr;
}
foreach
语句或者您可以只使用递归foreach
语句。
$obj = (your_object_here);
var_dump(flat($obj));
function flat($iterable) {
$arr = [];
foreach ($iterable as $key => $element) {
if (is_array($element) || is_object($element)) {
$arr = array_merge($arr, (array)flat($element));
} else {
$arr[$key] = $element;
}
}
return (object)$arr;
}