How to access an element in an array in PHP - php

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.

Related

Use php to display specific "key-value" pair from the data retrieved from the mongodb

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']

Can't retrieve associative array index in php

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.

php Undefined index when I dont use a redundant if statement

I have a multidimensional array that I want to access and change one of the values from an integer to a string using a helper function. The code below works but if I remove the if statement which I dont really need it gives me a Undefined index error on the helper code
$stories = multidimensional array in this format
array(1) {
[0]=> array(4)
{
["code"]=> string(1) "2"
["user_name"]=> string(4) "Dave"
["name"]=> string(11) "project one"
["sample_id"]=> string(1) "2"
}
}
to access the array I am using
foreach($stories as $key => $subarray) {
if(array_key_exists('code', $subarray)){
//if($stories[$key]['code'] > 0){
$stories[$key]['code'] = task_priority_text($stories[$key]['code']);
//};
}
}
Commenting the code in this way throws the error while uncommenting gives a clean result.
Here is the helper function which I have used elsewhere and works well
if ( ! function_exists('task_priority_text'))
{
function task_priority_text($priority = FALSE)
{
$options = array('0' => 'Urgent', '1' => 'High', '2' => 'Medium', '3' => 'Low', '4' => 'Minimal');
if($priority !== FALSE)
return $options[$priority];
else
return $options;
}
}
How do I get ride of this if statement?
EDIT
here is the error
A PHP Error was encountered
Severity: Notice
Message: Undefined index: Medium
Filename: helpers/tasks_helper.php
Line Number: 70
line 70 of the helper is
return $options[$priority];
You are looping over each item in the array multiple times. The 'outer' loop runs once for every item in the array, then the 'inner' loop (which someone else pointed out is redundant) runs again for every item in the $subarray variable.
foreach($stories as $key => $subarray) {
foreach($subarray as $subkey => $subsubarray) {
if(array_key_exists('code', $subarray)){
//if($stories[$key]['code'] > 0){
$stories[$key]['code'] = task_priority_text($stories[$key]['code']);
//};
}
}
}
This would be a better way of doing it:
foreach($stories as $story)
{
$story['code'] = task_priority_text($story['code']);
}

Laravel: object unable to access its properties

Let's say I have a function which returns an object with one of it's parameters set to some certain value:
public function search($jobsdone, $date)
{
foreach ($jobsdone as $jd) {
if ($jd->date_worked == $date) return $jd;
}
}
Printing search($jobsdone, $key) yields such results:
object(JobDone)#378 (19) {
...
["attributes":protected]=>
array(9) {
["id"]=>
int(3593)
["user_id"]=>
int(13)
["object_id"]=>
int(99)
["job_id"]=>
int(130)
["date_worked"]=>
string(10) "2013-10-01"
["min_from"]=>
int(780)
["min_to"]=>
int(1080)
}
...
}
However, if I want to print out search($jobsdone, $key)->id, all I get is an error message of:
Trying to get property of non-object
What could I be missing here?
Your search function doesn't always return an object. Therefore, you get error Trying to get property of non-object whenever your search couldn't find a $jobdone object.

Get all object from a "group" in PHP from JSON array

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.

Categories