Array包含一些非空数组。我需要获取相应的非空数组并打印数据。例如:数组2的变量为importTroubles-> troubleMessage我该如何打印?
Array
(
[0] => stdClass Object
(
)
[1] => stdClass Object
(
)
[2] => stdClass Object
(
[return] => stdClass Object
(
[failureMessage] =>
[importTroubles] => stdClass Object
(
[kind] => ParseError
[rowNumber] => 1
[troubleMessage] => Field "number1" has invalid value: "+16046799329". Invalid phone number //need to print this..
)
[keyFields] => number1
[uploadDuplicatesCount] => 0
[uploadErrorsCount] => 1
[warningsCount] => stdClass Object
(
)
[callNowQueued] => 0
[crmRecordsInserted] => 0
[crmRecordsUpdated] => 2
[listName] => new camp from CRM1-TargetList-CRM
[listRecordsDeleted] => 0
[listRecordsInserted] => 2
)
)
[3] => stdClass Object
(
)
[4] => stdClass Object
(
)
)
我尝试使用这种方法:
foreach($result as $object) {
foreach ($object as $items) {
if($items !== '')
{
foreach ($items as $item) {
echo "ERROR".$item->troubleMessage;
}
}
}
}
感谢您的努力
答案 0 :(得分:1)
利用php函数empty()
更改您的if条件,如下面的代码:
foreach($result as $object) {
foreach ($object as $items) {
if( !empty($items) )
{
foreach ($items as $item) {
if( isset($item->troubleMessage) )
{
echo "ERROR".$item->troubleMessage;
}
}
}
}
}
现在只有$items
有值时才会回显。
答案 1 :(得分:0)
将您的if($items !== '')
更改为if(!empty($items))
或if($items)
或if($items[0])
希望有所帮助
答案 2 :(得分:0)
如果您只是寻找嵌套在其中的单个特定项目,则不必迭代每个对象。您可以直接参考该项目。
foreach ($your_array as $object) {
if (isset($object->return->importTroubles->troubleMessage)) {
echo $object->return->importTroubles->troubleMessage;
}
}
如果检查是否设置了特定的嵌套对象变量,它将忽略任何空对象。
答案 3 :(得分:0)
您可以使用Collection
use Illuminate\Support\Collection;
$collection = new Collection($result);
$items = $collection->filter(function($object) {
return isset($object->return->importTroubles->troubleMessage);
})->map(function($object) {
return $object->return->importTroubles->troubleMessage;
});