How to loop my data for PHP - php

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;

Related

How can I sort values from an existing array by data type?

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";
}

getting element names and values of json respsonse php

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!!

How can I call particular array value of array in php?

I'm getting below output as an array.
$array =
Array
(
[12] => Array
(
[1] => Array
(
[14] => Array
(
[0] => Array
(
[name] => Avaya Implementation Services
[service_id] => 14
[ser_type_id] => 1
[service_desc] =>Avaya Implementation Servic
)
)
)
)
);
I want to print only service_desc array value. and I don't want call like $array[12][1][14][0]['service_desc'];
How can I call particular service_desc array value of the array?
As you mentioned that you don't want to call it as $array[12][1][14][0]['service_desc'] you can use extract function which will create variables from your array,
extract($array[12][1][14][0]);
echo $service_desc;
And then you can use your particular key such as service_desc as variable.
You can try this function: (Please optimize as per your requirements)
$arr ="<YOUR ARRAY>";
$val = "service_desc";
echo removekey($arr, $val);
function removekey($arr, $val) {
$return = array();
foreach ($arr as $k => $v) {
if (is_array($v) && $k !== $val) {
removekey($v, $val);
continue;
}
if ($k == $val) {
echo ($arr[$k]);
die;
}
$return[$k] = $v;
}
return $return;
}
You can use array_walk_rescursive to frame a single dimensional array of matching keys:
DEMO
<?php
$array[12][1][14][0]['service_desc'] = 'Avaya Implementation Servic';
$array[12][1][14][0]['service'] = 'dsfasf';
$array[12][1][114][0]['service_desc'] = 'Avaya Implementation Servicasdfdsf';
$searchKey = 'service_desc';
$desiredValues = [];
array_walk_recursive($array, function ($v, $k) use ($searchKey, &$desiredValues) {
if ($k === $searchKey) {
$desiredValues[] = $v;
}
});
print_r($desiredValues);
So this will yield:
Array
(
[0] => Avaya Implementation Servic
[1] => Avaya Implementation Servicasdfdsf
)
You might use the array_walk_recursive function.
array_walk_recursive($array, function ($val, $key) {
if ($key == 'service_desc') print_r($val);
} );
Instead of the print_r statement, you can collect your data into another structure, which you convey using the use statement, or with the $userdata additional parameter (see http://www.php.net/manual/en/function.array-walk-recursive.php ).
$results = array();
array_walk_recursive($array, function ($val, $key) use (&$results) {
if ($key == 'service_desc') {
$results []= $val;
}
} );
Pay extra care to the & in front of the use (&$results) otherwise your array of results will be considered immutable inside the callback (i.e. all changes discarded).
Convert multidimensional array to single array using iterator_to_array
REF: http://php.net/manual/en/function.iterator-to-array.php
$service_desc= iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($your_array)), 0);
print_r($service_desc);
Result:
Array
(
[name] => Avaya Implementation Services
[service_id] => 14
[ser_type_id] => 1
[service_desc] =>Avaya Implementation Servic
)

Sum arrays in php

I have the result from database.
Array
(
[0] = stdClass Object
(
[name] = First
[sum] = 3,8,...
)
[1] = stdClass Object
(
[name] = Second
[sum] = -1,0,...
)
[2] = stdClass Object
(
[name] = Third
[sum] = 2,-1...
)
)
So now I need to sum all in column "sum".
I need to get result like
$final = (4, 7,...);
I have transformed sum to array throw explode() and then tried with foreach
for example
foreach ($result as $k=>$subArray) {
$arrayNumbers = explode(",",$subArray->sum);
foreach ($arrayNumbers as $key => $value) {
$sumArray[] = $value];
$stepToSum2[] = array_sum($sumArray);
}
unset($arrayNumb);
}
Not sure that my example working because I'm already stuck with commented code.
Anyway, I with some manipulations I can get or sum right for the first numbers (5) or the sum of my array (11).
The same result with this
$sum = array_sum(array_map(function($var) {
return $var['sum'];
}, $myResultArray));
I have searched for the answer but most of the answers only for two arrays, but in same tables, I have more than 5 arrays, so I can't figure out how to implement this.
array_reduce is good for reducing an array to a single value as you're doing here. It takes an array and a function that updates a "carry" value for each item in your array.
$result = array_reduce($your_array, function($carry, $item) {
foreach (explode(',', $item->sum) as $key => $value) {
$carry[$key] = $value + (isset($carry[$key]) ? $carry[$key] : 0);
// (OR $carry[$key] = $value + ($carry[$key] ?? 0); in PHP 7)
}
return $carry;
}, []);
Since you're already creating an array:
foreach ($result as $subArray) {
$arrayNumbers[] = explode(",", $subArray->sum);
}
$first = array_sum(array_column($arrayNumbers, 0));
$second = array_sum(array_column($arrayNumbers, 1));
Try this :
foreach ($result as $k => $subArray) {
$arrayNumbers = explode(",",$subArray->sum);
foreach ($arrayNumbers as $key => $value) {
$sumArray[$key] = isset($sumArray[$key]) ? $sumArray[$key] : 0;
$sumArray[$key] += $value;
}
}
print_r($sumArray);

Trying to read StdClass Object in PHP

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/>";
}

Categories