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;
}
Related
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;
});
I try to create an generic object which needs to be structuered like this:
[Content] => stdClass Object
(
[item] => Array
(
[0] => stdClass Object
(
[Value] => STRING
)
)
[item] => Array
(
[0] => stdClass Object
(
[Value] => ANOTHER STRING
)
)
)
This is my code:
$content = new stdClass();
$data = file('filname.csv');
foreach($data as $key => $val) {
$content->item->Value = $val;
}
This overwrites itself each time the loop iterates. By defining item as an array like this:
$content->item = array();
...
$content->item[]->Value = $val;
...the result is also not the estimated.
You are overwritting data each time even using array. You should create temporary object for storing value and then put them to item array.
$content = new \stdClass();
$content->item = array();
foreach($data as $key => $val) {
$itemVal = new \stdClass();
$itemVal->Value = $val;
$content->item[] = $itemVal;
}
This question already has answers here:
How to find entry by object property from an array of objects?
(13 answers)
Closed 9 years ago.
I have following std Object array
Array
(
[0] => stdClass Object
(
[id] => 545
)
[1] => stdClass Object
(
[id] => 548
)
[2] => stdClass Object
(
[id] => 550
)
[3] => stdClass Object
(
[id] => 552
)
[4] => stdClass Object
(
[id] => 554
)
)
I want to search for value of [id] key using loop. I have following condition to check whether value is exist or not like below
$flag = 1;
if(!in_array($value->id, ???)) {
$flag = 0;
}
Where ??? I want to search in array of std Object's [id] key.
Can any one help me for this?
If the array isn't too big or the test needs to be performed multiple times, you can map the properties in your array:
$ids = array_map(function($item) {
return $item->id;
}, $array);
And then:
if (!in_array($value->id, $ids)) { ... }
try:
foreach ($array as $val) {
if (!in_array($id, (array) $val)) {
...
}
}
Why not just cast the objects as arrays:
foreach ($array as $a) {
if (!in_array($id, (array) $a)) {
...
}
}
Assuming your array is names $yourArray ,
$newArr = array();
foreach ($yourArray as $key=>$value) {
$newArr[] = $value->id;
}
And now $newArr is like : array(545,548,550,552,554)
AND you can search in it by :
$valueOfSearch = ... ;
$flag = 1;
if(!in_array($valueOfSearch,$newArr)) {
$flag = 0;
}
I have an object which contains an array, which contains an array, which contains an object:
stdClass Object
(
[path] => Array
(
[0] => Array
(
[0] => SimpleXMLElement Object
(
[0] => 44.6451471575972
)
)
)
)
What I need to turn that into is this:
stdClass Object
(
[path] => Array
(
[0] => Array
(
[0] => 44.6451471575972
)
)
)
Basically I need to get rid of that object, but save the value in that object. Using PHP, how do I do this?
EDIT: Here the code I am using to create the array:
$xml = simplexml_load_file('/Users/jasonburton/Sites/walkabout/csv-importer/xml/'.$old_route_id.'.xml');
$nodes = $xml->xpath('/markers/line/*');
$json = new stdClass;
$json->path = array();
foreach($nodes as $node){
foreach($node->attributes() as $index=>$value){
$values[] = $value;
if(count($values) == 2){
$json->path[] = array($values[0], $values[1]);
unset($values);
$values = array();
}
}
}
print_r($json);
$value is what contains the SimpleXMLObject that needs to be converted into the value.
Thanks!
Type cast $value with string: $values[] = (string)$value;
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 />';
}
}