accessing multidimensional array in laravel blade - php

I'm trying to access the 'cat' value in my array below, coming from my controller.
If I dump $tempCategories it shows the array correctly but my html is showing nothing for some reason.
Am I not accessing the element correctly?
I expect to see
Wood
Metal
controller.php
$tempCategories = array(
0 => array(
'cat' => 'Wood'
),
1 => array(
'cat' => 'Metal'
),
);
blade.php
#foreach($tempCategories as $cat)
<h5>{{$cat->cat}}</h5>
#endforeach

You are trying to access an array as object
Replace
<h5>{{$cat->cat}}</h5>
With
<h5>{{$cat['cat']}}</h5>

If you want to access it with arrow operator - convert your array to object or collection first (in your controller)
$object = (object) $array;
Or
$collection = collect($array);

Related

Difference between $object->attribute and $object['attribute'] in Laravel

I'm developing with DataTables in Laravel and trying to make an object manually using collect() to create a collection. When I push the collection into the DataTable, there is something wrong, and I can't call my object with this $object->attribute.
After I get the error with that, I already tried to call an attribute with $object['attribute'], and it works well.
Can someone give me insight about the differences and how I can convert $object['attribute'] into $object->attribute?
This is my query to create object
$result = collect();
$item = collect([
'row' => ($key+1),
'item_id' => $value->uid,
'item' => $value->nama_item,
'sub_kategori' => $value->sub_jenis_item->sub_jenis_item,
'kategori' => $value->jenis_item->jenis_item,
'gudang_id' => $id_gudang
]);
$result->push($item);
Accessing $object['attribute'] means $object is an array and accessing $object->attribute means $object is an object.
To convert array to object:
$object = (object) $object;
Additionally, to convert object to array:
$object = (array) $object;
DataTables calls internally toArray() on the collection items when you build the table. This happens during transformation of the data. It will also flatten nested objects (e.g. loaded Eloquent relations in case of an EloquentDataTable) into an array with depth 1 (per row of the table).
You can try the following way,
$result = collect();
$item = collect([
'row' => ($key+1),
'item_id' => $value->uid,
'item' => $value->nama_item,
'sub_kategori' => $value->sub_jenis_item->sub_jenis_item,
'kategori' => $value->jenis_item->jenis_item,
'gudang_id' => $id_gudang
]
);
$result->push($item);
$resultObj = json_decode($result);
foreach($resultObj as $obj){
echo $obj->row;
}

Array in functions Yii Framework

can someone tell me what is this code doing, As im new to Yii, learning about it.. im not able to understand few things.. Here is the code..
$allmsg = LogMsg::model()->findAll($criteria); //
$dataArr = array();
if (isset($allMsg) && sizeof($allMsg) != 0):
foreach ($allMsg as $msg) {
$dataArr[$msg->date][] = array( // array?
'category' => $msg->category, // what is that 'category' a variable or something else? and $msg->category, is what?
'time' => $msg->time,
'date' => $msg->date,
'user' => $msg->name
);
} endif;
$this->render('index', array(
'data' => $dataArr ) //what is that 'data'?
);
My question is, what is this line of code doing exactly in foreach loop
$dataArr[$msg->date][] = array(
'category' => $msg->category,
and here is second code... which has something like that..
$allCat = Categories::model()->findAll($criteria);
$catArr=array();
if(isset($allCat) && sizeof($allCat)!=0):
foreach ($allCat as $catModel) {
$catArr[$catModel->id] =$catModel;
}
endif;
return $catArr;
so what is this line doing in this code in foreach loop, what is different between these two lines in first and second code..
$catArr[$catModel->id] =$catModel;
last thing.. what is it
public static function getID($category)
{
$arr = array(
'ast'=>1, // what are these things? from where are they coming? db?
'fp'=>5, //
'per'=>3,
'ts'=>6,
'lg'=>3
);
return isset($arr[$category])?$arr[$category]:null; //Ternary - Condensed if/else statement
}
So as per your first question.
$dataArr[$msg->date][] = array(
'category' => $msg->category,
$allMsg is the active record object which u get through the db query. This object is traversed in a loop and each row is "$msg".
Hence you can access the attributes of the model through the $msg->category. 'category' here is the attribute of the model.
this is creating multidimensional array.
Your first question
$dataArr[$msg->date][] = array(
'category' => $msg->category,
will generate output like
[2016-03-04] => Array
(
[0] => Array
(
[category] => abc
)
)
And your second question
$catArr[$catModel->id] =$catModel;
will genrate output like
array(
[0] =>1,
[1] => 2,
[2] => 3,
)
Not tested.
I think, your question is not about Yii. You should read about arrays of PHP first. In the code multidimensional array have been used. It means that the array can contain another array as value.

laravel blade how to set the options for drop down list

I am trying to create an drop down list using blade
I have already checked this question Laravel 4 blade drop-down list class attribute
I tried this:
{{Form::select('category_id', $categories)}}
and the result is:
<select name="category_id"><option value="0">{"id":2,"name":"Apartment"}</option><option value="1">{"id":3,"name":"Car"}</option></select>
I couldn't know how to show just the name value of the options. plus I couldn't know how to set the value of each option to its id
I know the forth parameter is the option one, and I tried to do this
{{Form::select('category_id', $categories, '', $categories)}}
but I got this exception:
htmlentities() expects parameter 1 to be string, array given (View:
please notice that the $categories is array, each row has id and name
Update 1
I send the value from controller to view like this
$categories = Category::All(['id', 'name']);
where Category is a model
Form::select() requires a flat array like
array(
1 => 'Appartment',
2 => 'Car'
)
whereas $categories = Category::all() gives you a multidimensional array that looks like
array(
0 => array(
'id' => 1,
'name' => 'Appartment'
),
1 => array(
'id' => 2,
'name' => 'Car'
)
)
That being said just change
$categories = Category::all(['id', 'name']);
to
$categories = Category::lists('name', 'id');
Then this will work just fine
{{ Form::select('category_id', $categories) }}

Cakephp - How to loop through array in email template?

I am able to set the viewVars for a single record and mail it successfully. A problem occurs when I want to send an email containing more than one record. I find the correct records and I am able to pass them to my mail function. The problem comes in that when I debug the array passed to the mail template, I get a
Notice (8): Undefined variable: vars [APP\View\Emails\html\latest_projects.ctp, line 1]
However, just below the error, it does show me the information I want:
(int) 0 => array(
'Project' => array(
'id' => '809',
'created' => '2014-04-23',
'project_number' => 'SPN00000809',
)
),
(int) 1 => array(
'Project' => array(
'id' => '810',
'created' => '2014-04-23',
'project_number' => 'SPN00000810',
)
)
*Certain fields omitted for brevity.
How do I loop through this array in the email template? I have tried the standard foreach loop as you would in the view, but then I get the undefined variable supplied foreach problem. Any advice or suggestions?
//Pass your variable
$Email->viewVars(array('projects' => $projects));
//In your email body or template
<ul>
<?php foreach ($projects as $project) { ?>
<li><?php echo $project['Project']['project_number']; ?></li>
<?php } ?>
</ul>
like said in documentation :-
$Email->viewVars(array('value' => 12345));
you will be able to use it as $value in mail template.
just like that set your array to 'value' you will be able to use $value as array.
The problem was that the array passed, $dataForView, which is generated by cake, was a combination(?) array - meaning that some keys were associative such as $dataForView['content'] => '', while the other keys were (int)0 => array();
The array received looked as such:
array(
content => '',
(int) 0 => array(
Project => array(
fieldName1 => value,
fieldName2 => value
)
),
(int) 1 => array(
Project => array(
fieldName1 => value,
fieldName2 => value
)
)
)
I found that if I unset the associative keys (content) I am able to loop through the normalized array as per usual. I did it in this way, it might not be the best way, but it works.
//remove associative key
unset($dataForView['content']);
//loop through array and output values
foreach($dataForView as $key=>$val):
echo $val['Project']['id']; //echo other info as well
endforeach;
debug($dataForView);
Thank you all for helping.

converting config ini like string dot separated value to actual array keys

got a multidimensional array and a string in a config and i need to transform it as an array key without the use of eval. Real world use of this problems is that i got a big document from mongodb that is transformed into multi dimensional array. However i need to define specific array nodes from a config file.
the idea is to create a config file as representation of the array key's hierarchy
on the config.ini the values below are some example.
colorattribute = attribute.color
wholesaleprice = prices.wholesale
Example Response from mongoDb
<?php
$products = array(
'product_name' => 'iTouch',
'brand_name' => 'Apple',
'attributes' => array ( 'color' => 'black',
'size' => '5 in'
),
'prices' => array(
'wholesale' => 135,
'retail' => 200,
),
);
function recurseKeys(array $keys,array $array){
$key = array_shift($keys);
if(!isset($array[$key])) return null;
return empty($keys) ?
$array[$key]:
recurseKeys($keys,$array[$key];
}
var_dump(recurseKeys(explode('.',$testConfig),$products);

Categories