Trying to read StdClass Object in PHP - 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/>";
}

Related

PHP associate array

I have a output of print_r below and I want to access all the individual elements value with foreach loop but unfortunately I am unable to do that via foreach. Could anyone please help me with the associate array question.
I can access via this $arr['Level1'][Date] and it returns value as "2015-04-14 07:15".
But how to get all the element values via foreach loop?
Array
(
[Level1] => Array
(
[Date] => 2015-04-14 07:15
[img1] => pic1
[img2] => pic2
[InnerLevel] => Array
(
[0] => value1
[1] => value2
)
)
[Level2] => Array
(
[Date] => 2015-04-15 08:15
[img1] => pic1
[img2] => pic2
[InnerLevel] => Array
(
[0] => value3
[1] => value4
)
)
)
<?php
foreach ($myarray as $level => $itemArr) {
if(is_array($itemArr)) {
foreach ($itemArr as $levelArr) {
if(is_array($levelArr)) {
foreach ($levelArr as $key => $interlevelValue) {
echo $interlevelValue;
}
} else {
echo $levelArr;
}
}
} else {
echo $itemArr;
}
}
?>
foreach ($myarray as $item) {
echo $item['Date'] . "\n";
}
The fact that the array is associative or not doesn't change anything.
$item is successively a copy of $myarray['Level1'] then $myarray['Level2'] (etc. if more) in the foreach loop.
It depends on index depth.
To extract simple associative arrays like:
$mainarray['Name']='Value';
Use:
foreach ($mainarray as $aname=>$avalue)
{
echo $aname." in ".$mainarray." = ".$avalue." <br>";
}
To extract deeper associative arrays like:
$mainarray['Child']['Name']='Value';
Use:
foreach ($mainarray as $aname=>$asubarray)
{
echo "In ".$aname." from ".$mainarray."...<br>";
foreach ($asubarray as $asubname=>$asubvalue){
echo $asubname." = ".$avalue." <br>";
}
echo "<br>";
}
This:
<br>
represents new line. If you're running the code from a command line or you just want text only output, then use this for a new line:
\n
Actually there is another way of doing this in php.
"Iterating over Multidimensional arrays is easy with Spl Iterators :
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($iterator as $key=>$value) {
echo $key.' -- '.$value.'<br />';
}
This will iterate through all possible iterable objects.
See
http://php.net/manual/en/spl.iterators.php
http://www.phpro.org/tutorials/Introduction-to-SPL.html
" - Quoted from - https://stackoverflow.com/a/2149106/1766122 answered by #Gordon

Get items in multidimensional array separately

I have an array ($myArray) like this:
print_r(array_values ($myArray));
result: Array (
[0] =>
[1] => Array (
[id] => 1
[name] => ABC
)
[2] => Array (
[id] => 2
[name] => DEF
)
)
I'm trying to get each ID and NAME.. So Im trying this:
foreach ($myArray as $value) {
foreach($value as $result) {
echo $result;
}
}
I'm facing two problems:
I get a PHP WARNING that says: " Invalid argument supplied for foreach() on line 29
This line is: foreach($value as $result) {
I would like to get keys to ID and NAME to place them in correct places. This ways echo "1ABC" and "2DEF"
Any idea? Thanks for helping.
Basically, the error triggered, since the array in your example (index zero in particular) is not an array (most likely an empty string/null ) which is being used inside foreach.
Since one of the elements is not an array, you could just check that if its an array or not using is_array():
foreach($myArray as $values) {
if(is_array($values)) {
echo $values['id'] . ' ' . $values['name'] . '<br/>';
}
}
Alternatively, you could also use array_filter() in this case which in turn removes that empty index zero, so that you could just use that loop that you have. You wouldn't have to check for that empty element.
$myArray = array_filter($myArray);
foreach ($myArray as $value) {
foreach($value as $result) {
echo $result;
}
}
try this,
foreach (array_slice($myArray ,1) as $value) {
foreach($value as $result) {
echo $result;
}
}
the 1st position is empty so omit first position

How to loop my data for 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;

Question related to array

I'm trying to print array. All code working fine.But at last I'm getting `ArrayArray'. Can any one solve this problem. many many thanks
here is my array
Array
(
[Post1] => Array
(
[id] => 1
[title] => hi
)
[Post2] => Array
(
[0] => Array
(
[id] => 1
)
)
[Post3] => Array
(
[0] => Array
(
[id] => 1
)
)
)
Here is my PHP Code
foreach($post as $key => $value) {
foreach($value as $print => $key) {
echo "<br>".$key;
}
}
here is output
ID
Array
Array
Try this:
foreach($post as $key => $value) {
foreach($value as $print => $key) {
if (is_array($key)){
foreach($key as $print2 => $key2) {
echo "<br>".$key2;
}
}else{
echo "<br>".$key;
}
}
}
The to string method of an array is to return "Array".
It sounds like you want to view the array for debugging purposes. var_dump() is your friend :)
you are trying to print an array, resulting in Array.
If you want to print an array use print_r
I think the trouble for you is that you have $key in the outer loop and $key in the inner loop so its really confusing which $key you are talking about for starters.
You just want the stuff printed out to debug?
echo "<pre>" . print_r( $post , true ) . "</pre>\n";

Any idea how I pull those values?

foreach ($_GET as $field => $label) {
$datarray[]=$_GET[$field];
echo "$_GET[$field]";
echo "<br>";
This is the output I am getting. I see the data is there in datarray but when I echo $_GET[$field] I only get "Array"
But print_r($datarray) prints all the data. Any idea how I pull those values?
OUTPUT:
Array (
[0] => Array (
[0] => Grade1
[1] => ln
[2] => North America
[3] => yuiyyu
[4] => iuy
[5] => uiyui
[6] => yui
[7] => uiy
[8] => 0:0:5
)
)
foreach ($_GET as $key => $value)
{
if(is_array($value))
{
foreach($value as $childKey => $childValue)
{
echo $childKey." ".$childValue; // or assign them to an array
}
}
else
echo $key." ".$value; // or assign them to an array
}
Seems like $_GET[$field] is basically $_GET[0], which is an array:
You'll have to loop through $_GET[$field] with a forloop to get the content to echo out. By the way you can't echo array you'll have to use print_r
something like this:
foreach ($_GET as $field => $label) {
$datarray[]=$_GET[$field];
for($i=0; $i<$_GET[$field]; $i++){
echo $_GET[$field][$i];
}
echo "<br>";
}
EDIT: When I completed your test, here was the final URL:
http://hofstrateach.org/Roberto/process.php?keys=Grade1&keys=Nathan&keys=North%20America&keys=5&keys=3&keys=no&keys=foo&keys=blat&keys=0%3A0%3A24>
This is probably a malformed URL. When you pass duplicate keys in a query, PHP makes them an array. The above URL should probably be something like:
http://hofstrateach.org/Roberto/process.php?grade=Grade1&schoolname=Nathan&region=North%20America&answer[]=5&answer[]=3&answer[]=no&answer[]=foo&answer[]=blat&time=0%3A0%3A24
This will create individual entries for most of the fields, and make $_GET['answer'] be an array of the answers provided by the user.
Bottom line: fix your Flash file.

Categories