How to fetch non-empty Array from an Array - php

The Array contains some non-empty arrays . i need to fetch respective non-empty array and print the data . eg: array 2 has variable as importTroubles->troubleMessage how can i print that?
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
(
)
)
im trying with this method :
foreach($result as $object) {
foreach ($object as $items) {
if($items !== '')
{
foreach ($items as $item) {
echo "ERROR".$item->troubleMessage;
}
}
}
}
Thanks for your efforts

Make use of php function empty()
Change your if condition as in below code :
foreach($result as $object) {
foreach ($object as $items) {
if( !empty($items) )
{
foreach ($items as $item) {
if( isset($item->troubleMessage) )
{
echo "ERROR".$item->troubleMessage;
}
}
}
}
}
Now it will echo only if $items has values.

You don't have to iterate each object if you're only looking for a single specific item nested within it. You can just refer to that item directly.
foreach ($your_array as $object) {
if (isset($object->return->importTroubles->troubleMessage)) {
echo $object->return->importTroubles->troubleMessage;
}
}
If you check if that specific nested object variable is set, it will ignore any empty objects.

change your if($items !== '') to if(!empty($items)) or if($items) or if($items[0]) hope it helps

You could use 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;
});

Related

Accessing Std Class Object values from JSON string in PHP

I am receiving a JSON string from an API, which I am then decoding into an array. The array is full of stdClass Objects and arrays, but I cannot seem to access the properties.
This is the array I have decoded from JSON and then called print_r on:
stdClass Object
(
[scannedDocument] => stdClass Object
(
[scanId] => 6188703b5450ed927159cbbbb223fc89
[totalWords] => 7
[totalExcluded] => 0
[credits] => 1
[creationTime] => 2019-10-21T10:33:18
)
[results] => stdClass Object
(
[internet] => Array
(
)
[database] => Array
(
)
[batch] => Array
(
)
[score] => stdClass Object
(
[identicalWords] => 0
[minorChangedWords] => 0
[relatedMeaningWords] => 0
[aggregatedScore] => 0
)
)
[status] => 0
)
I am assuming I should access the first value of the array and then using -> to get to the object values like this:
$wordcount = $jsonResponse[0]->scannedDocument->totalWords;
$totalExcluded = $jsonResponse[0]->scannedDocument->totalExcluded;
$percent = $jsonResponse[0]->results->score->aggregatedScore;
But these variables are blank. I am tearing my hair out!
Any ideas please?
You can convert your object to array or stdClass and access it using one of those function according to object type
function ConvertToObject($array) {
$object = new stdClass();
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = ConvertToObject($value);
}
if (isset($value)) {
$object->$key = $value;
}
}
return $object;
}
function ConvertToArray($obj) {
if (is_object($obj))
$obj = (array) $obj;
if (is_array($obj)) {
$new = array();
foreach ($obj as $key => $val) {
$new[$key] = ConvertToArray($val);
}
} else {
$new = $obj;
}
return $new;
}

php - How to unset array element in this condition

My array looks like this:
Array (
[0] => Array (
[value] => Array (
[source] => vimeo
[url] => https://vimeo.com/000000
)
[type] => videos
)
[2] => Array (
[value] => 62
[type] => images
)
)
I want to unset the array id with the type => images.
I tried this:
$key = array_search('images',$slides);
unset($slides[$key]);
and it only deletes the first item in the array!!!
Update:
After all, I did it this way:
foreach ( $slides as $slide => $value) {
if ($display_mode == 'images' && $value['type'] == 'videos') {
unset($slides[$slide]);
} elseif ($display_mode == 'videos' && $value['type'] == 'images') {
unset($slides[$slide]);
}
}
Thank you.
foreach ($slides as $key => $slide) {
if (in_array('images', $slide)) unset($slides[$key]);
}
array_search returns false if $needle is not found. false casts to 0 when used as an integer. You might want to consider array_filter for your use case:
$array = array(...);
$array = array_filter($array, function($item) { return in_array('images', $item); });

PHP Accessing SimpleXMLElement Object array keys

In the following SimpleXMLElement Object $results, I would like to remove the element with ID 13011146 from the TEST array. I'm not sure how to properly access the array key with value 1, so I'm using a counter $i, but that gives me an error Node no longer exists, pointing to the foreach line.
TL;DR: How do you unset $result->TEST[1] ?
SimpleXMLElement Object
(
[TEST] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[ID] => 13011145
)
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[ID] => 13011146
)
)
)
)
PHP:
$i = 0;
foreach($results->TEST as $key => $value) {
if( (string)$value['ID'] == 13011146 ) {
unset($results->TEST[$i]);
}
$i++;
}
try this
$node = $results->children();
unset($node[1]);
foreach($results->TEST->children() as $key => $value) {
$attributes = $value->attributes();
foreach($attributes as $a => $b) {
if (( (string)$a == 'ID' ) && ( (string)$b == '13011146' )) {
unset($results->TEST[$key]);
}
}
}
a more elegant way; it gives you the same results without using $attributes[ '#attributes' ] :
$attributes = current($element->attributes());
For specific key/value pair, we can use like:
$attributes = current($value->attributes()->NAME);
Hope it helps !
Try this:
$sxe = new SimpleXMLElement($xml);
foreach ($sxe->children() as $child){
foreach($child as $key=>$item){
echo $key.': '.$item.'<br />';
}
}

How to go a level up in an array?

I want would like to get the parent node of the array below, but I don't find a way to easily do this.
Normally for getting the id, I would do this in PHP:
echo $output['posts']['11']['id'];
But how can I get to the parent node "11" when I get the value of "id" passed from a $_GET/$_POST/$_REQUEST? (ie. $output['posts']['11'][$_GET[id]])
Array
(
[posts] => Array
(
[11] => Array
(
[id] => 482
[time] => 2011-10-03 11:26:36
[subject] => Test
[body] =>
[page] => Array
(
[id] => 472
[title] => News
)
[picture] => Array
(
[0] => link/32/8/482/0/picture_2.jpg
[1] => link/32/8/482/1/picture_2.jpg
[2] => link/32/8/482/2/picture_2.jpg
[3] => link/32/8/482/3/picture_2.jpg
)
)
)
)
$parent = null;
foreach ($array['posts'] as $key => $node) {
if ($node['id'] == $_GET['id']) {
echo "found node at key $key";
$parent = $node;
break;
}
}
if (!$parent) {
echo 'no such id';
}
Or possibly:
$parent = current(array_filter($array['posts'], function ($i) { return $i['id'] == $_GET['id']; }))
How this should work exactly depends on your array structure though. If you have nested arrays you may need a function that does something like the above recursively.
array_keys($output['posts']);
will give you all keys within the posts array, see http://php.net/manual/en/function.array-keys.php
you could try with something like:
foreach ($posts as $post){
foreach( $items as $item){
if ( $item['id'] == [$_GET[id] ){
// here, the $post is referring the parent of current item
}
}
}
I don't think it is possible while an array of array is not a DOM or any tree structure. In an array you can store any reference. but you can not naturally refer to an array containing a reference.
Check rolfs example for array_filter at php manual http://www.php.net/manual/en/function.array-filter.php#100813
So you could do it like this
$filtered = array_filter($output, function ($element) use ($_GET["id"]) { return ($element["id"] == $_GET["id"]); } );
$parent = array_pop($filtered);

foreach loop problem

Foreach don't work properly because in the a array there are multiple arrays and also objects.
For example:
Array
(
[0] => modelItem Object
(
[name] => Name 1
[option] => Array
(
[0] => modelOption Object
(
[id] => 28383
[price] => 1.70
)
)
[quantity] => 2
)
[1] => modelItem Object
(
[name] => Name 2
[option] => Array
(
[0] => modelOption Object
(
[id] => 28398
[price] => 3.50
)
)
[quantity] => 2
)
[subtotal] => 10.40
[deliveryArea] => modelDeliveryArea Object
(
[postcode] => BL2
)
[delivery] => 1
)
I want foreach only loop on modelItem Object and modelItem Object only, how can that be done?
I have tried doing this:
<?php
foreach ($items as $key => $item) {
echo $item->name;
foreach ($item->option as $o) {
echo $o->price;
}
}
?>
It work fine but I also get an error:
Warning: Invalid argument supplied for foreach()
This is because of subtotal, deliveryArea I think.
Edit: Sorry, fixed the loop code - forgot to add { }
Try:
<?php
foreach ($items as $key => $item) {
if ($item instanceof modelItem) {
echo $item->name;
if (isset($item->option) && is_array($item->option)) {
foreach ($item->option as $o) {
echo $o->price;
}
}
}
}
Okay, the reason your code doesn't work, is because you are mixing types of your arrays. Which means you're going to have problems if you always expect $item to be a class. IF you can, I recommend restructuring your array so that your modelItem objects are in an array by themselves to make life easier.
If you cant... Try this:
<?php
if (is_array($items)) {
foreach ($items as $key => $item) {
if(is_a($item, 'modelItem')) {
echo $item->name;
foreach ($item->option as $o) {
echo $o->price;
}
}
}
}
As a side note is_a() is deprecated in php 5.0 - 5.2 and is now undeprecated in php 5.3. If you are using php 5.0 - 5.2 see yoshi's example.
In array like this I would recommend to check like this:
if(isset($someVar))
{
}
or in your case check if is_array like this:
if(is_array($something))
{
}
You can not loop trough a string in your case subtotal, deliveryArea
I hope it helps!

Categories