I'm trying to catch all objects in PHP from a JSON array, I need all the objects that will appear under ["Elements"]. So how would this be possible if I:
1.) Don't know the "name" of the object and don't know the content inside it.
2.) What I would like to achieve is to get the first objects value inside Elements, and then get the "content" inside of it, regardless of the names (there could be multiple objects)
Here is a var_dump of the JSON:
object(stdClass)#1 (1) {
["Canvas"]=>
array(1) {
[0]=>
["Elements"]=>
object(stdClass)#18 (2) {
["textHolder2"]=>
object(stdClass)#19 (1) {
["textContent"]=>
string(12) "Text to edit"
}
["textHolder1"]=>
object(stdClass)#20 (1) {
["textContent"]=>
string(12) "Text to edit"
}
}
}
}
}
Use foreach.
$json = json_decode( $input, true );
$elems = $json['canvas']['Elements'];
foreach( $elems as $key => $value ) {
echo "{$key} is an array/object:\n";
echo var_dump( $value );
}
You could use array_keys() if you need to know what keys are inside $value or you could another foreach loop, but I am assuming you will have at least some clue what keys could be in $value.
Related
I have a $_SESSION index called "items".
Just like this:
$_SESSION['items'];
When user click to add item I check if $_SESSION['items'] exists. If exists, then insert the item, if not, create and insert. Ok.
So I coded this solution:
$newItem = array(
'id'=>$this->getId(),
'red'=>$this->getRef()
);
if(isset($_SESSION['items'])) {
array_push($_SESSION['items'],$newItem);
} else {
$_SESSION['items'] = $newItem;
}
Ok.
The problem is:
If the "else" occurs, the $newItem array is pushed into $_SESSION['items'] with this structure:
{
0: {
id: "1",
ref: "0001",
}
}
Exactly as I was expecting.
But if the "if" statement occurs, my $_SESSION['item'] looses the new indexes and I get a structure like this:
{
0: {
id: "1",
ref: "0001",
},
id: "2",
ref: "0001",
}
As you can see, the new item is not set as array...
If I add more itens, the issue affects only the last item added...
What I am doing wrong?
Change your code to the following:
if (isset($_SESSION['items'])) {
array_push($_SESSION['items'],$newItem);
} else {
$_SESSION['items'] = [];
array_push($_SESSION['items'], $newItem);
}
Now, all the $newItems will be pushed in to an actual array.
Output
array(1) {
["items"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(2) "id"
["ref"]=>
string(3) "ref"
}
[1]=>
array(2) {
["id"]=>
string(4) "id-2"
["ref"]=>
string(5) "ref-2"
}
}
}
Live Example
Repl - Dummy data used
Your array_push here seems to be problem, because when you are pushing the array in $_SESSION[‘items’] it takes $newItem array elements and pushes them in the $_SESSION[‘items’]
If you can do as below then it should work
$newItem = array(
'id'=>$this->getId(),
'red'=>$this->getRef()
);
$_SESSION['items'][]= $newItem;
Hi I am trying to access a property of an object from an array but seems to not getting it correctly. I have an array of objects that is posted in PHP.
$classrooms = $_POST->client->classrooms
when I do a var_dump($classrooms) I get the structure like below:
array(1) {
[0]=>
array(2) {
[0]=>
object(stdClass)#5 (4) {
["classroomid"]=>
int(2)
["classroom"]=>
string(7) "Grade 1"
}
[1]=>
object(stdClass)#6 (4) {
["classroomid"]=>
int(4)
["classroom"]=>
string(9) "Grade 2"
}
}
}
I am trying to access "classroom" property using following code in PHP but it does not output anything.
foreach($classroom as $item)
{
echo $item['classroom'];
}
But if try like this (by hardcoding index) it gives me correct name of classrooms but I cannot pass the index as I do not know how many will be in the array.
foreach($classroom as $item)
{
echo $item[0]['classroom'];
}
Thank you for reading this.
Try like this,
$lists = [];
foreach($classroom as $item)
{
foreach($item as $k => $v){
$lists[] = $v->classroom; // or $v->classroom;
}
}
print_r($lists);
For stdClass object you have to use "->" to get the key value.
foreach($classroom as $subarray) {
foreach($subarray as $item) {
echo $item->classroom;
}
}
If you use $item['classroom'] it will throw an error:
PHP Fatal error: Uncaught Error: Cannot use object of type stdClass as array.
This is the php code.
<?php
// connect to mongodb
$m = new MongoClient();
// select a database
$db = $m->Example;
$collection="User";
$Query = array("Username"=>$username);
$j = $db->$collection->find($Query);
foreach ($j as $k) {
echo"<pre>";var_dump($k); echo"</pre>";
}
foreach($j as $k => $v) {
echo $k.'='.$j[$k].'<br>';
}
?>
In this, the data is retrieved in $j variable an when var_dump($k) is used the output is as follows:
array(8) {
["_id"]=>
object(MongoId)#6 (1) {
["$id"]=>
string(24) "56d1cb49097ed3241d000029"
}
["Fname"]=>
string(4) "Ritu"
["Lname"]=>
string(3) "Rad"
["Username"]=>
string(4) "riri"
["Password"]=>
string(4) "riri"
["Email"]=>
string(23) "ritikatra#gmail.com"
}
But if you try to display individual key value pair as in the next foreach loop you get the following error:
Fatal error: Cannot use object of type MongoCursor as array
How to display only a particular key and it's value?
eg: Email ritikatra#gmail.com
Result of \MongoCollection::find() (your $j) variable is an instance of \MongoCursor class which implements \Iterator - it allows you to loop over it but it doesn't have keys (i.e. doesn't implement \ArrayAccess). If you want to use your results as an array you should call
$array = iterator_to_array($j);
Now you can use $array as it'd be plain array:
echo $array[0]['Email']
I have this json code:
$cars = '{
"CarBenz":
[
{
"Car": "Benz",
"Color": "Black"
}
]
}';
$json = json_decode($cars , true);
how to print Benz in screen?
print $json['Car'];
$json['Car'] nothing show anything.
To see the type of a variable (and how an object or array is built up) you can use var_dump($json).
In this case, that will give:
array(1) {
["CarBenz"]=>
array(1) {
[0]=>
array(2) {
["Car"]=>
string(4) "Benz"
["Color"]=>
string(5) "Black"
}
}
}
So you need to do $json['CarBenz'][0]['Car'].
First you can var_dump your decoded json string and you can see the array with the structure.
I think you forgot to access the CarBenz element first.
echo $json['CarBenz'][0]['Car'];
If you need all elements in CarBenz you have to iterate over them. Something like that:
foreach($json['CarBenz'] as $car) {
echo $car;
}
I have an array that looks like the following:
array(3) { [0]=> array(1)
{
["habitacionales"]=> array(1)
{ ["Azcapotzalco"]=> string(1) "3" } }
[1]=> array(1) { ["comerciales"]=> array(0) { } }
[2]=> array(1) { ["industriales"]=> array(0) { } }
}
And I need to check if the array belongs to the type "habitacionales", or "comerciales", etc. But no matter what I do, I keep getting the notice "Undefined index: habitacionales". Could someone point out how to access that index?
I am using cakephp, and I am setting the variables in the controller like this:
$zonasHab = $this->PropiedadesHabitacionale->BasicosPropiedadesHabitacionale->find('list', array('fields'=>array('Zona', 'propiedad_habitacional_id')));
then I do:
$this->set('Zonas', array_unique($linksZonas, SORT_REGULAR));
And finally in the view I do:
foreach ($Zonas as $zona) {
foreach($zona as $zone) {
foreach(array_flip($zone) as $link) {
echo '<li class="dropdownheader">'.$link;
}
var_dump($zone['habitacionales']);
}/*
if($zona['habitacionales']!=null)
foreach(array_flip($zone) as $vinculo) {
echo '<li>'.$this->Html- >link($vinculo, array('controller'=>'propiedadeshabitacionales', 'action'=>'ver', $vinculo)).'</li>';
}
*/
echo '</li>';
}
Just to point out, the wierd thing is that if I do var_dump($zona['habitacionales']); inside the outer foreach, I get the correct value: array(1) { ["Azcapotzalco"]=> string(1) "3" } but I still get the notice appearing telling me it's an undefined index, and I can't use that same syntax ($zona['habitacionales'] for a condition or anything else.
Assuming $Zonas is that array above, try:
foreach($zona as $zone) {
foreach(array_flip($zone) as $link) {
echo '<li class="dropdownheader">'.$link;
}
var_dump($zone);
habitacionales is the key, if you want to access that then use:
foreach($zona as $key => $zone) {
And $key should be set to habitacionales.