I would like to get all the elements and their values from the json response. I have the following response (snippet, it has more elements):
stdClass Object ( [Count] => 15244 [Warnings] => Array ( ) [Machines] => Array ( [0] => stdClass Object ( [Id] => 23 [Modified] => 2019-09-18 06:38:04 [Created] => 2016-03-10 14:11:39 ) [1] => stdClass Object ( [Id] => 51 [Modified] => 2019-09-18 08:15:52 [Created] => 2016-06-15 09:13:16 )))
Now I would like to get the results something like:
ID: 23, Modified: 2019-09-18 06:38:04, Created: 2016-03-10 14:11:39
ID: 51, Modified: 2019-09-18 08:15:52, Created: 2016-06-15 09:13:16
The problem is, that I don't want to hard-code the element names like "ID", "Created" and so on, because the complete array per Machines has about 50 elements.
This is what I tried:
$obj = json_decode($body);
foreach ($obj->Machines as $comp) {
$sup =key($comp);
echo key($comp)."-".$comp->$sup."<br>";
}
But this only gives the output:
Id-23
Id-51
So I only get the first KEY showed. I don't know how to get to the next element like "Modified" in the loop.
Thanks for the support!
You can use array map to echo the same,
foreach ($obj->Machines as $comp) {
echo implode(', ', array_map(function ($val, $key) {
return sprintf("%s:'%s'", $key, $val);
}, $comp, array_keys($comp)))."<br/>";
}
Solution 2:-
foreach ($obj->Machines as $comp) {
echo str_replace('=',':',http_build_query($comp,'',', '));
}
http_build_query — Generate URL-encoded query string
Convert your JSON data to array using json_decode(). Make an iteration over the array using array_map(), again make another nested iteration using array_walk() to replace the value to key:value pear format. Finally join the converted array to string by the glue of comma.
Code example:
$response = json_decode($response, true);
$result = array_map(function ($val) {
array_walk($val, function (&$v, $k) { $v = "$v: $k"; });
return implode(',', $val);
}, $response);
print_r($result);
What you did is correct, though this is a multi-dimensional array.
You need several foreach loops to iterate to the dimension you want.
$response = [];
foreach($obj->Machines as $comp) {
foreach($comp as $key => $value) {
$response[$key] = '';
foreach($value as $title => $display) {
$response[$key] .= $title . ': ' . $display . ', ';
}
$response[$key] = rtrim($response[$key], ', ');
}
}
var_dump($response);
This is what did the trick now:
$obj = json_decode($body);
print_r($obj);
//echo $obj->Machines[0]->Id;
foreach ($obj->Machines as $comp) {
echo "<BR>";
foreach($comp as $key => $value){
echo $key.":".$value." - ";
}
}
Gives the output like:
Id:148 - Modified:2019-09-18 07:16:47 - Created:2016-11-08 08:21:36
Id:143 - Modified:2019-09-15 04:13:21 - Created:2016-11-04 05:34:01
Again, really great support again! thank you very much!!
Related
I try to determine the data type of each array value from an existing array using foreach() and var_dump().
Let's say I have this array: example:
$arr = ['this','is', 1, 'array', 'for', 1, 'example'];
Now I have to take each value of this field and determine its data type.
I try this:
$str = array();
$int = array();
foreach($arr as $k => $val) {
if(var_dump($arr[$k]) == 'string'){
$str[] = $arr[$k];
} else {
$int[] = $arr[$k];
}
}
In other words, I try to sort the values from an existing array by data type and create a new array with only 'string' values and a second new array with only 'int' values. But it seems that my 'if' condition isn't working properly. How else could I solve this please? Thank you.
You need to use gettype to get the type of a value, not var_dump:
foreach($arr as $k => $val) {
if(gettype($arr[$k]) == 'string'){
$str[] = $arr[$k];
} else {
$int[] = $arr[$k];
}
}
Output:
Array
(
[0] => this
[1] => is
[2] => array
[3] => for
[4] => example
)
Array
(
[0] => 1
[1] => 1
)
Demo on 3v4l.org
Use gettype
$data = array('this','is', 1, 'array', 'for', 1, 'example');
foreach ($data as $value) {
echo gettype($value), "\n";
}
I decoded a JSON array which contained keys and values in PHP. The JSON looks like this (shortened for easier understanding):
[{"code":"123"},{"identification":"Some item"},{"price":"$20"}]
After I json_decode'd it, it looked like this:
Array ( [0] => stdClass Object ( [code] => 123 ) [1] => stdClass Object ( [identification] => Some item ) [2] => stdClass Object ( [price] => $20 ) )
How can I read both the key and the value?
I already tried searching on SO all over and already tried something like this:
foreach ($jarray as $key) {
echo 0->$key;
}
which throws an 500 (ISE) error.
Also tried this:
foreach ($jarray as $key => $value) {
echo $key;
echo $value;
}
which also throws an 500 error.
I don't know how to accomplish this...
EDIT: Basically, I just want to iterate trough the whole thing and get key and value every time, like this:
code - 123
identification - Some item
price - $20
...
$json = '[{"code":"123"},{"identification":"Some item"},{"price":"$20"}]';
$jarray = json_decode($json, true);
foreach ($jarray as $value) {
foreach ($value as $key => $val) {
echo $key;
echo $val;
}
}
I hope so it will reduce loop process confusion and simple to do this task.
$text = '[{"code":"123"},{"identification":"Some item"},{"price":"$20"}]';
$array = json_decode($text);**strong text**
foreach($array as $value)
{
$array = (array)$value;
$x = each($array);
echo $x['key'];
echo "====>>>>";
echo $x['value'];
echo "<br/>";
}
I have a PHP array with multiple objects. I'm trying to join values from a certain key into one string separated by commas. Output from var_dump:
Array
(
[0] => stdClass Object
(
[tag_id] => 111
[tag_name] => thing 1
[tag_link] => url_1
)
[1] => stdClass Object
(
[tag_id] => 663
[tag_name] => thing 2
[tag_link] => url_2
)
)
The string needs to be $string = 'thing 1,thing 2'. I tried using a foreach loop, but I'm completely stuck. Could anyone help out?
The above answer is a little light, maybe run it as a foreach loop instead.
$names = array();
foreach ($array as $k => $v) {
$names[] = $v->tag_name;
}
$string = implode(',', $names);
$output = '';
foreach($test as $t){
$output .= $t->tag_name . ',';
}
$output = substr($output, 0, -1);
echo $output;
Try as this
$string = $array[0]->tag_name.','.$array[1]->tag_name;
For other elements
$string = '';
foreach($array as $object) $string.=$object->tag_name.',';
$string = substr($string,0,-1);
Use something like this:
implode(',', array_map(function ($el) {
return $el->tag_name;
}, $array));
I have some data which was json decoded and looks like this:
stdClass Object
(
[6] => stdClass Object
(
[13] => stdClass Object
(
[buildingId] => 1
)
)
[8] => stdClass Object
(
[20] => stdClass Object
(
[Id] => 1
)
)
Thing is i don't know how to loop to get the information to use it in my script.
I need to get for example:
$key, $innerkey, $Id = 1
Object [8][20].Id = 1
The two numbers are X;Y co ordinates so its important i get those values aswell as the id.
I managed to get the first key:
$obj = JSON_decode($_GET['data']);
foreach($obj as $key) {
echo $key;
}
How do i get the innerkey assigned to a variable ?
Change json_decode($_GET['data']); to json_decode($_GET['data'], true);
If the second parameter is true then it return the array else it is object.
$obj = json_decode($_GET['data'], true);
foreach($obj as $key=>$val) {
foreach($val as $k=>$v){
echo $k." : ".$v['Id'];
echo "<br>";
}
}
Ref: http://php.net/manual/en/function.json-decode.php
You need to wrap numeric keys with {}. Kind of a PHP caveat.
echo $obj->{8}->{20}->Id;
Do you mean this?
$array = (array)json_decode($_GET['data']);
foreach ($array as $key) {
var_dump($key);
}
or
$array = json_decode($_GET['data'], true);
foreach ($array as $key) {
var_dump($key);
}
json_decode()'s 2. parameter: true: to array, false: to object.
You have to use two foreach loops for this as below
$obj = JSON_decode($_GET['data']);
foreach($obj as $key) {
foreach($key as $val) {
echo $val->id;
}
}
updated answer
$obj->{8}->{20}->Id = 10; // assigned the value for testing purpose.
$a = 8;
$b = 20;
echo $obj->$a->$b->Id;
my php array looks like this:
Array (
[0] => dummy
[1] => stdClass Object (
[aid] => 1
[atitle] => Ameya R. Kadam )
[2] => stdClass Object (
[aid] => 2
[atitle] => Amritpal Singh )
[3] => stdClass Object (
[aid] => 3
[atitle] => Anwar Syed )
[4] => stdClass Object (
[aid] => 4
[atitle] => Aratrika )
) )
now i want to echo the values inside [atitle].
to be specific i want to implode values of atitle into another variable.
how can i make it happen?
With PHP 5.3:
$result = array_map(function($element) { return $element->atitle; }, $array);
if you don't have 5.3 you have to make the anonymous function a regular one and provide the name as string.
Above I missed the part about the empty element, using this approach this could be solved using array_filter:
$array = array_filter($array, function($element) { return is_object($element); });
$result = array_map(function($element) { return $element->atitle; }, $array);
If you are crazy you could write this in one line ...
Your array is declared a bit like this :
(Well, you're probably, in your real case, getting your data from a database or something like that -- but this should be ok, here, to test)
$arr = array(
'dummy',
(object)array('aid' => 1, 'atitle' => 'Ameya R. Kadam'),
(object)array('aid' => 2, 'atitle' => 'Amritpal Singh'),
(object)array('aid' => 3, 'atitle' => 'Anwar Syed'),
(object)array('aid' => 4, 'atitle' => 'Aratrika'),
);
Which means you can extract all the titles to an array, looping over your initial array (excluding the first element, and using the atitle property of each object) :
$titles = array();
$num = count($arr);
for ($i=1 ; $i<$num ; $i++) {
$titles[] = $arr[$i]->atitle;
}
var_dump($titles);
This will get you an array like this one :
array
0 => string 'Ameya R. Kadam' (length=14)
1 => string 'Amritpal Singh' (length=14)
2 => string 'Anwar Syed' (length=10)
3 => string 'Aratrika' (length=8)
And you can now implode all this to a string :
echo implode(', ', $titles);
And you'll get :
Ameya R. Kadam, Amritpal Singh, Anwar Syed, Aratrika
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
echo $item->atitle;
}
}
to get them into an Array you'd just need to do:
$resultArray = array();
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
$resultArray[] = $item->atitle;
}
}
Then resultArray is an array of all the atitles
Then you can output as you'd wish
$output = implode(', ', $resultArray);
What you have there is an object.
You can access [atitle] via
$array[1]->atitle;
If you want to check for the existence of title before output, you could use:
// generates the title string from all found titles
$str = '';
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$str .= $v->title;
}
}
echo $str;
If you wanted these in an array it's just a quick switch of storage methods:
// generates the title string from all found titles
$arr = array();
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$arr[] = $v->title;
}
}
echo implode(', ', $arr);
stdClass requires you to use the pointer notation -> for referencing whereas arrays require you to reference them by index, i.e. [4]. You can reference these like:
$array[0]
$array[1]->aid
$array[1]->atitle
$array[2]->aid
$array[2]->atitle
// etc, etc.
$yourArray = array(); //array from above
$atitleArray = array();
foreach($yourArray as $obj){
if(is_object($obj)){
$atitleArray[] = $obj->aTitle;
}
}
seeing as how not every element of your array is an object, you'll need to check for that.