how to pass multidimensional array (having numeric keys ) from controller to template? - php

My controller code is as below,
$errorData = array(1) {
["val_0"]=>
array(2) {
["created_at"]=>
string(0) ""
["user_email"]=>
string(29) "email address cannot be empty"
}
}
there may be val_1, val_2.... etc.
I just want to pass this array $errorData to template and print it in foreach loop.
How can I do that. I am not able to get what variable to be called in template to access those messages.
Thanks

In your controller, pass data array as below:
$data["error"] = $errorData;
$this->load->view("VIEW_FILE",$data);
In view, your $data extracted. so you will get your error array as $error
foreach($error as $e) // val_0, val_1....
{
//$e is now having val_0 at first loop run
echo $e["created_at"];
echo $e["user_email"];
}

Related

PHP Check if Key Exists in Multidimensional Array and Object Combination then Get Value

I am querying an API and the response I get is a Multidimensional Object object(stdClass) that also contains arrays. I need to be able to check if the response is an error condition or was successful. If the response is successful I need to return TRUE. If the response was an error, I need to return the error message contained in the response. The response formats for success and error are completely different. The response for an error looks like this:
object(stdClass)#837 (3) {
["errors"]=> array(1) {
[0]=> object(stdClass)#838 (2) {
["code"]=>int(324)
["message"]=>string(80) "Duration too long, maximum:30000, actual:37081 (MediaId: snf:840912013693931526)"
}
}
["httpstatus"]=>int(400)
["rate"]=>NULL
}
The response for success looks like this:
object(stdClass)#837 (27) {
["created_at"]=> string(30) "Sun Mar 12 13:41:43 +0000 2017"
["id"]=> int(840920745073102850)
["id_str"]=> string(18) "940920795073102850"
["text"]=> string(32) "The Details Posted Here"
["truncated"]=> bool(false)
["entities"]=> object(stdClass)#838 (5) {
["hashtags"]=>
........ Way More is in the Response but it does not matter...
I have tried changing the response to an array then using isset to establish if it was an error, and if so then get the values of the error details like so:
$RESPONSEARRAY = (array) $RESPONSE;
(isset($RESPONSEARRAY["errors"])) {
$ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]['code'];
$ERRORMSG_MESSAGE = $RESPONSEARRAY['errors'][0]['message'];
$ITWASANERROR = $ERRORMSG_CODE.": ".$ERRORMSG_MESSAGE;
return $ITWASANERROR;
} else {
return true;
}
But doing the above give me the following error:
Fatal error: Cannot use object of type stdClass as array
Can anyone suggest a way of doing what I am trying to do with the least overhead on the server. Maybe without needing to convert the stdClass object to an array, or if that has to be done, then that's fine, but I just need it to work. Any help someone can offer would be super appreciated.
Below is the correct way to access the object inside the array.
$RESPONSEARRAY = (array) $RESPONSE;
if(isset($RESPONSEARRAY["errors"])) {
$ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]->code;
$ERRORMSG_MESSAGE = $RESPONSEARRAY['errors'][0]->message;
$ITWASANERROR = $ERRORMSG_CODE.": ".$ERRORMSG_MESSAGE;
return $ITWASANERROR;
} else {
return true;
}
$RESPONSEARRAY = (array) $RESPONSE;
You can get result:
["errors"]=>
array(1) {
[0]=>
object(stdClass)#1 (2) {
["code"]=>
int(324)
["message"]=>
string(80) "Duration too long, maximum:30000, actual:37081 (MediaId: snf:8
40912013693931526)"
}
}
["httpstatus"]=>
int(400)
So $ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]['code']; should be $ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]->code.
And so on

How to access an element in an array in 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.

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.

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.

Passing Array from Model to Controller to View in CodeIgniter

I have a model that sends an error response to the controller in CodeIgniter that then is passed to the view which is just a JSON encoder. Here is the array from the model.
return $posts[] = array('complete'=>0,'error'=>1003, 'message'=>'Username already exists');
The issue I am having is that I need those square brackets after the $posts variable because sometimes I need an array of errors. However when I pass the single array to the view it encodes the JSON without the square brackets but when I have multiple arrays it includes the square brackets, I need the square brackets in the JSON every time. Here is the Controller...
$data['data'] = $this->logins_model->signup($post_data);
$this->load->view('json', $data);
Here is the view...
header('Content-type: application/json');
$response['response'] = $data;
echo json_encode($response);
I need the JSON response to look like this
{
"response": [
{
"complete": 0,
"error": 1003,
"message": "Username already exists"
}
]
}
NOT THIS!
{
"response": {
"complete": 0,
"error": 1003,
"message": "Username already exists"
}
}
Since you want to get array in json you should be having it in php array as well (i.e. data-structures should meet). So $response['response'] = $data; should be $response['response'] = array($data);
In your example var_dump($response); gives:
array(1) {
["response"]=>
array(3) {
["complete"]=>
int(0)
["error"]=>
int(1003)
["message"]=>
string(23) "Username already exists"
}
}
As you see $response['response'] is an object for json.
When you replace $response['response'] = $data; with $response['response'] = array($data); your data-structure, which you want to convert in json will become:
array(1) {
["response"]=>
array(1) {
[0]=>
array(3) {
["complete"]=>
int(0)
["error"]=>
int(1003)
["message"]=>
string(23) "Username already exists"
}
}
}
That will give you desired output because json_encode will expect that there might be another items in $response['response'].
Demo
Edit
Your model should be returning one dimensional array. For example:
return array('complete'=>0,'error'=>1003, 'message'=>'Username already exists');
And you should assign it to another array that is holding all error messages:
$data['data'][] = $this->logins_model->signup($post_data);
$this->load->view('json', $data);
Demo 2
In your view define $post as an array and remove tha square brackets from there. To check your results in view use print_r instead of echo. Which will show exactly how many data is retrieved.

Categories