How to parse an object containing multidimensional array - php

I have an object $userStatus which is fetching the values in the following format via an API call.
I am unable to allocate the values via loop.
foreach($usersStatus as $user => $element) {
print "[".$user."] => ". $element ."<br />";
}
The following script in php allows me to print the first set of values until the key ["total_time"] => String96) "6m 34s" but then I get a following warning
Warning: Array to string conversion in C:\XAMPP\htdocs\Check-status.php on line 119
[units] => Array
Is there a way, I can traverse the whole object including the two arrays [0][1] using a loop and assign any value to any variable.
I know vardump will print the whole thing, but I want to traverse the whole object via loop or nested loops.
["role"]=>string(7) "learner"
["enrolled_on"]=>string(20) "05/01/2021, 17:44:53"
["enrolled_on_timestamp"]=>string(10) "1609868693"
["completion_status"]=>string(9) "Completed"
["completion_percentage"]=>string(3) "100"
["completed_on"]=>string(20) "06/01/2021, 16:58:23"
["completed_on_timestamp"]=>string(10) "1609952303"
["expired_on"]=>string(0) ""
["expired_on_timestamp"]=>NULL
["total_time"]=>string(6) "6m 34s"
["units"]=>array(2) {
[0]=>array(8) {
["id"]=>string(4) "2047"
["name"]=>string(26) "MyCourse1 2019"
["type"]=>string(19) "SCORM | xAPI | cmi5"
["completion_status"]=>string(9) "Completed"
["completed_on"]=>string(20) "06/01/2021, 16:58:23"
["completed_on_timestamp"]=>string(10) "1609952303"
["score"]=>NULL
["total_time"]=>string(6) "3m 56s"
}
[1]=>array(8) {
["id"]=>string(4) "2059"
["name"]=>string(34) "Assessment - MyCourse1"
["type"]=>string(4) "Test"
["completion_status"]=>string(9) "Completed"
["completed_on"]=>string(20) "06/01/2021, 15:06:56"
["completed_on_timestamp"]=>string(10) "1609945616"
["score"]=>string(5) "91.67"
["total_time"]=>string(6) "2m 38s"
}
}
Thank you for your help!

Check if $element is array to avoid this
foreach($usersStatus as $user => $element) {
// check if the value is not array
if (!is_array($element)) {
print "[".$user."] => ". $element ."<br />";
} else {
// value is array do with it whatever you want
// like another foreach for example
foreach($element as $key => $value) {
// do whatever
}
}
}

array_walk_recursive will satisfy your example. It will apply a user function to every member of an array while recursively doing so if the type is an array.
array_walk_recursive($arr, function ($val, $key) {
echo "[" . $key . "] => " . $val . "<br />";
});

Related

How can I access individual values in an associative array in PHP?

I am pulling elements from a standard class object into an assoc array like so:
$array = $subjects;
foreach ( $array as $subject ) {
foreach ( $subject as $prop => $val ) {
if ( $val !== '' ) {
echo $prop . ' = ' . $val;
echo "<br>";
}
}
}
I get the result I expect from above, except what I'd like to do is echo out individual values into a table.
When I do this:
echo $subject['day1'];
I get this: "Cannot use object of type stdClass as array."
Where am I going wrong? Thanks in advance.
If it's using StdClass you'll need to do this:
$subject->day1
If you want to convert it to an array, have a look at this question: php stdClass to array
You are trying to iterate over the $array and $array is still an object. Use this:
$vars = get_object_vars($subjects);
to get assoc. array from the object $subjects. Then go:
foreach ($vars as $name => $value) {
echo $name . "=" . $value;
echo "<br>";
}

Run a php foreach loop on multi-dimensional array

I need to run a foreach script on a multi-dimensional array.
The original JSON is formatted like:
{
"_links":{
},
"chatter_count":15,
"chatters":{
"moderators":[
"moderator1",
"moderator2",
"moderator3"
],
"staff":[
"staff1",
"staff2",
"staff3"
],
"admins":[
"admin1",
"admin2",
"admin3"
],
"global_mods":[
"global_mod1",
"global_mod2",
"global_mod3"
],
"viewers":[
"viewer1",
"viewer2",
"viewer3"
]
}
}
Having run json_decode to get a PHP data structure, I'm now lost on how to run a foreach loop to output something like:
chatter_count: 15
moderators:
moderator1
moderator2
moderator3
staff:
staff1
staff2
staff3
admins:
admin1
admin2
admin3
global_mods:
global_mod1
global_mod2
global_mod3
viewers:
viewer1
viewer2
viewer3
First decode the json to array, then make use of $key to print the array:
<?php
$testobj = json_decode(file_get_contents('https://tmi.twitch.tv/group/user/sodapoppin/chatters'), true);
echo "chatter_count:".$testobj['chatter_count']."\n";
foreach($testobj['chatters'] as $key => $chatter){
echo "\n$key:\n";
foreach ($chatter as $value) {
echo "$value\n";
}
}
Output:
I get something like this from the URL you gave:
chatter_count:5461
moderators:
emilydk
fyzicul
hnl
hnlbot
ngmack
nixi93
psychostatik
sodapoppin
staystrong420
sxyhxy
tastyphone
staff:
evoli
pluto
...
...
...
You are just few step behind what you're trying to accomplish. To get chatter_count use $testobj ->chatter_count. And then loop through your chatters array use foreach($testobj->chatters as $key => $value) { // write your logic here }. This way you can get what you're trying to accomplish. I can paste the code here, but I would like you to give a try first. Hope you get your hints now.
PHP
$data = json_decode($json, true);
echo "chatter_count: " . $data["chatter_count"] . "\n";
foreach($data['chatters'] as $chattersK=> $chatters) {
echo $chattersK . ":\n";
foreach($chatters as $chatterK => $chatters) {
echo $chatters . "\n";
}
echo "\n";
}
Demo: Eval.in
Try this code.
And you have to add some style for print.
$testobj = json_decode(file_get_contents("https://tmi.twitch.tv/group/user/sodapoppin/chatters"));
print("chatter_count:", $testobj->chatter_count);
foreach ( $testobj->chatters as $key=>$chatter )
{
print $key;
foreach($chatter as $values){
printf("%s\n", $values);
}
}
Hoping this helps you.

How to Convert Nested array to Value in PHP?

My arrays
a:3:{s:6:"Choice";a:2:{i:0;s:5:"First";i:1;s:6:"Second";}s:5:"fcode";s:26:"form_rajas_exmsw2rpc81anlj";s:9:"useremail";s:26:"rajasekarang.cud#gmail.com";}
array (
'Choice' =>
array (
0 => 'First',
1 => 'Second',
),
'fcode' => 'form_rajas_exmsw2rpc81anlj',
'useremail' => 'rajasekarang.cud#gmail.com',
)
my php code
$arrays = 'a:3:{s:6:"Choice";a:2:{i:0;s:5:"First";i:1;s:6:"Second";}s:5:"fcode";s:26:"form_rajas_exmsw2rpc81anlj";s:9:"useremail";s:26:"rajasekarang.cud#gmail.com";}';
$decode = unserialize($arrays);
foreach($decode as $key => $value) {
echo '<td width="100">' . $value . '</td>';
}
My Error is :
Notice: Array to string conversion in....
The first Values in Nested Array.
How to convert nested array as a Value?
I need to show like this,
<tr><td>First,Second</td><td>form_rajas_exmsw2rpc81anlj</td><td>rajasekarang.cud#gmail.com</td></tr>
If $value is an array, you need a nested loop.
foreach ($decode as $key => $value) {
if (!is_array($value)) {
$value = array($valule);
}
foreach ($value as $subvalue) {
echo "<td width='100'>$subvalue</td>";
}
}
If you can have multiple levels of nesting, you should write a recursive function that handles each level.
If you want a sub-array to be shown as a comma-separated list, you can use implode.
foreach ($decode as $key => $value) {
if (is_array($value)) {
$value = implode(', ', $value);
}
echo "<td width='100'>$subvalue</td>";
}
you have nested array populated with elements of diferent size so you will always get an error. so in your foreach loop, you can check if the value is an array or not, like for instance
if (count($value)>1){
//code here like for instance echo $value[0]...
}//not recomended becuse an array can have only one value, but you can if you know you will put at least 2
or
if(is_array($value)..
Me I will do the following:
foreach($thing as $thingy =>$that){
//check if array or not
if(is_array($that)){
foreach($that as $t)
//do whatever
}else
//do whatever
}

fetch array and move array to object in php

while ($array = $photo_items->fetch_array()) {
echo $array['img_src'];
echo "<br />";
}
I don't want to use fetch object because I want this array to be within another object.
the current result is 1.jpg2.jpg
what I want is
{
otherproperty: 'something',
img : ['1.jpg'],['2.jpg'];
}
in json
You can do simply, try this way
$json_array = array('otherproperty' => "something", "img" => array())
while ($array = $photo_items->fetch_array()) {
array_push($json_array['img'], $array['img_src'])
}
echo json_encode($json_array);

My PHP foreach code is not working properly

I found that in PHP I can use two types of foreach.
Here is the code:
$p2 = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
echo "p2 element: " . $p2['inkjet'] . "<br>";
foreach ($p2 as $item => $desc)
{
echo "$item -> $desc <br />";
}
echo "<br />";
while (list($item, $desc) = each($p2))
{
echo "$item -> $desc <br />";
}
The second while loop does not iterate over the items. Why?
After the first foreach() is done, the internal "current position" indicator on the $p2 is at the END of the array. You need to reset() that pointers so the while() loop starts at the beginning again. e.g.
foreach($p2 as $item => $desc) {
....
}
reset($p2); // <--you need this
while(list(...) = ...) {
...
}
foreach() does this reset for you implicitly each time you foreach() the array, so if your code had been the other way around (while loop then the foreach), you wouldn't have this problem.

Categories