How does a foreach loop iterate through an object - php

I am getting the contents of a facebook api call that will return all the posts made to a facebook group. So all the posts/comments on that post.
$data = json_decode(file_get_contents($url2));
foreach($data as $post){
foreach $post as $subpost)
{
...etc
}
}
The problem I have here is that I will need to use 3 nested foreach loops in order to actually get the data I want. How do I get the first element of $data without having to use a foreach?
e.g. something like $data[0] (which doesn't work). How does a foreach loop iterate through an object so I can just manually write it since I only want 1 single object thats nested inside arrays.
edit
object(stdClass)#1 (2) { ["data"]=> array(25) { [0]=> object(stdClass)#2 (10)...
i want to access the final object that contains 10 pieces of data.

$data = json_decode(file_get_contents($url2), true);
will return an array and you can access it via an index like $data[0].

Try to use like below - just pass true in second argument , it will convert object into array so you can use it as array.
$data = json_decode(file_get_contents($url2), true);
foreach($data as $post){
foreach $post as $subpost)
{
...etc
}
}

You should do
$data = json_decode(file_get_contents($url2),true);
To convert it to a array then try
$data[0]

You can use $post instead of $data..
indexing of $post depends on what kind of data you are receiving through json.
If it is a 2-dimensional array,You can use $post[0]['index'] or if it is a single-dimensional array,you can use $post['index'], which will give you the exact indexed item.

Related

How to convert an object properties into an array in php

Those data in $data variable. When I'm using dd($data); I got this:
CurlHandle {#1918 ▼
+url: "https://example.com"
+content_type: "application/json; charset=UTF-8"
+http_code: 200
+header_size: 887
+namelookup_time_us: 139522
+pretransfer_time_us: 326662
+redirect_time_us: 0
+starttransfer_time_us: 668686
+total_time_us: 668752
}
I want to convert this data to an array.
I'm using this: $arr = json_decode($data,true);
But, this is not working. Now, how can I convert this?
You can use below solution
$yourArray = json_decode(json_encode($yourObject), true);
and this convert object to an array for more info
Objects are, in PHP, maybe iterable. Notice, you may iterate through an object's public fields only via the foreach loop. So the following works:
$array = [];
foreach ($object as $property) {
$array[] = $property; // Stores public field only
}
var_dump($array);
Simply to get an array of object properties, you may use the get_object_vars() function.
var_dump(get_object_vars($object));
You may cast an object to be an array as #MoussabKbeisy said. And this would be the easiest way:
$array = (array) $object;
Here is another way is using ArrayIterator:
$iterator = new ArrayIterator($object);
var_dump(iterator_to_array($iterator));
while this is a PHP Object so you can deal with it by 2 ways:
1- if you want to get on of it's parameters, you can simply use
$yourObject->parameter;
2- if you need to use convert and use it as array, then there is different ways to convert an object to an array in PHP
//1
$array = (array) $yourObject;
//2
$array = json_decode(json_encode($yourObject), true);
Also see this in-depth blog post:
Fast PHP Object to Array conversion

Loop trough JSON file with PHP

I have this part of a JSON file:
And the next record:
I need to get several fields from each record. For instance [City].
With this code I can get the first city:
$response = curl_exec($ch);
$result = json_decode($response, true);
echo $result['GetLocationsResult']['ResponseLocation'][0]['Address']['City'];
However I want to loop through all the records and get all [City] fields.
This should be quite straight forward
$locations = $result['GetLocationsResult']['ResponseLocation'];
$cities = [];
foreach($locations as $location)
{
$cities[] = $location['Address']['City'];
}
var_dump($cities);
This is a more modern approach to getting all the cities, we don't need any loop anymore:
$cities = array_map(
fn($location) => $location['Address']['City'],
$result['GetLocationsResult']['ResponseLocation']
);
print_r($cities);
It depends on what exactly you need from the array whether this suits.
The true param of the json_decode tells you that the decoded json is an associative array. Thus you can use it as an array an loop over the values you want as you would threat any other array.

Can't use JSON array in a php loop

i have a json file, that has to be parsed in a loop.
i cant seem to succeed
JSON:
{"IMD":{"url":"http:\/\/www.google.com","timeOut":1515155361},"cvH":{"url":"http:\/\/www.google.com","timeOut":1515155364}}
PHP:
<?php
$linkyValues="./linky.json";
if (file_exists($linkyValues)) {
$fileStream = fopen($linkyValues, 'r');
$fileValue=json_decode(fread($fileStream, filesize($linkyValues)));
fclose($fileStream);
echo count($fileValue);//Always 1!
for($i=0;$i<count($fileValue);$i++){
$timeout=$fileValue->item($i)->timeOut;
if(time()>=$timeout){
unset($fileValue[$i]);
}
}
$fileStream = fopen($linkyValues, 'w');
fwrite($fileStream, json_encode($fileValue));
fclose($fileStream);
}
?>
my problem is that count($fileValue) is always 1.
Output of var_dump($fileValue):
object(stdClass)#2 (2) {
["IMD"]=>
object(stdClass)#1 (2) {
["url"]=>
string(21) "http://www.google.com"
["timeOut"]=>
int(1515155361)
}
["cvH"]=>
object(stdClass)#3 (2) {
["url"]=>
string(21) "http://www.google.com"
["timeOut"]=>
int(1515155364)
}
}
it looks like an array to me...
JSON does not support the concept of an associative array, but stores such maps as objects instead.
Your JSON file contains such an object. For PHP this means, that it can either import it as an stdClass ( object ) or as an associatiave array.
This is decided by the json_decode's second parameter, that is either TRUE to read the object as an associative array, or FALSE to read it as an object.
Therefore this will fix your problem:
$fileValue = json_decode(fread($fileStream, filesize($linkyValues)), TRUE);
json_decode documentation
In addition to that, your code has problems with iterating the array. You use $fileValue->item($i) as well as $fileValue[$i], while you have an associative array.
You work with it as if it was an indexed array, while it is an associative array, which means it has keys instead of indices, that identify the values in your array.
The propper way to iterate an associative array is with foreach, like deomstrated belo:
foreach($fileValue as $key => $value) {
if (time() >= $value['timeOut']) {
unset($fileValue[$key]);
}
}
Yet, since you only want to remove specific values, you can use array_filter as well:
$fileValue = array_filter($fileValue, function($value){
return time() < $value['timeOut'];
});
array_filter will then take care of removing the specified fields from your array, so you do not have to unset them manually.
You can use :
count((array)$fileValue);
You're mixing up arrays and objects here.
count() can only be used on arrays, however you can cast an object to array to achieve the same thing.
$fileValue[$i] is a method to access an array, which won't work with your json object.
I see a solution already is to just change your object to an array so I'd like to offer the solution if you wanted to stick with objects.
$linkyValues="./linky.json";
if (file_exists($linkyValues)) {
$fileStream = fopen($linkyValues, 'r');
$fileValue=json_decode($jsonString);
fclose($fileStream);
//Cast the object to an array to get the count, but count isn't really requierd
echo count((array)$fileValue);
//loop through the object
foreach($fileValue as $key=>$fv){
//pull the timeout
$timeout=$fv->timeOut;
//do the check
if(time()>=$timeout){
//remove the timeout from the object
unset($fileValue->$key);
}
}
$fileStream = fopen($linkyValues, 'w');
fwrite($fileStream, json_encode($fileValue));
fclose($fileStream);
}
?>

read jquery array in php

i am trying to retrieve the value of array via post in php script.
var data = [];
table.rows({ selected: true }).every(function(index){
// Get and store row ID
data.push(this.data()[0]); //create a 1 dimensional array
});
//send data via ajax
$.ajax({
url: '/...../...',
type: 'POST',
data: {userid:data},
dataType: 'json',
In my PHP script so far I am unable to decode the array. Have tried many ways
$myArray = $_REQUEST['userid'];
foreach ($arr as $value) {
$userid= $value; //for now just trying to read single item
}
I have tried print_r($myArray ); this sucessfully prints array contents to screen.
I am trying to retrieve the values for processing! Kindly point me in the right direction
I don't think that PHP would recognise the array that you've called "data" as being an array. Couldn't you turn the data from your table rows into values in a JavaScript object, encode it as a JSON string, then post that to your PHP script and use json_decode($_POST["userid"]) on the PHP end to convert it into a PHP array.
The object you are posting to PHP isn't in particular a jQuery object. Instead it is an JSON object or rather a JSON string. I guess you can't read that object the way you would read an regular array in PHP.
You might want to try to decode the string with json_decode(). With true as an function argument, it will return an php array as suggested in this stackoverflow answer https://stackoverflow.com/a/6964549/6710876
$phpArray = json_decode($myArray, true);
Documentation of json_decode(): http://php.net/manual/en/function.json-decode.php
simply use:
echo json_encode($myArray);
You're foreach is looping $arr, which doesn't exist. Your array is being set to $myArray, so use that in your for.
$myArray = $_REQUEST['userid'];
foreach ($myArray as $value) {
$userid= $value; //for now just trying to read single item
}
I believe you should also be able to find your values in $_POST
According to your var_dump :
array(1) { ["userid"]=> string(21) "assssssss,camo,castor" }
and if we assume "assssssss,camo,castor" are 3 different usernames.
You should use this:
$userids=explode(",",$myArray->userid);
foreach($userids as $userid){
// use $userid
}

Get a specific recurring value from JSON array using PHP foreach loop

I have the following JSON array:
{"key1":"Example1","key2":"Example2","key3":"Example3","key4":"Example4","key1":"Example5","key2":"Example6","key3":"Example7","key4":"Example8","key1":"Example9","key2":"Example10","key3":"Example11","key4":"Example12"}
Using PHP is it possible to display a specific recurring value, for example if I wanted to display "key1" in a foreach loop it would return the following:
Example1
Example5
Example9
Appreciate any tips on what to use to do this, thanks.
You aren't going to be able to do this using json_encode because it's not valid JSON. (Keyspace collision)
You are going to need to assemble the object manually.
You might consider creating the individual items, then using implode(). Then you can prepend and append { and }.
<?php
$jsonObject='{"key1":"Example1","key2":"Example2","key3":"Example3","key4":"Example4","key1":"Example5","key2":"Example6","key3":"Example7","key4":"Example8","key1":"Example9","key2":"Example10","key3":"Example11","key4":"Example12"}';
$jsonArray = array_map(
function($array){
$keyValue=explode(":",$array);
return array("key"=>substr($keyValue[0],1,-1),"value"=>substr($keyValue[1],1,-1));
},
explode(
",",
substr($jsonObject,1,-1)
)
);
foreach($jsonArray as $object){
$output[$object['key']][]=$object['value'];
}
echo implode("\n",$output['key1']);
?>

Categories