'how to get value from array in laravel
In laravel i get this type of array from where query. i want to get only those menu where parent is 0;
$memus = Menu::where('parent', 0)->get()->toArray();
Array
(
[0] => Array
(
[id] => 13
[name] => Movies
[parent] => 0
[deleted_at] =>
[created_at] => 2015-04-07 02:48:48
[updated_at] => 2015-04-07 02:48:48
)
[1] => Array
(
[id] => 16
[name] => zxcvxc
[parent] => 0
[deleted_at] =>
[created_at] => 2015-04-07 02:53:26
[updated_at] => 2015-04-07 03:03:39
)
[2] => Array
(
[id] => 17
[name] => alsdkf
[parent] => 0
[deleted_at] =>
[created_at] => 2015-04-07 02:53:41
[updated_at] => 2015-04-07 03:02:04
)
)
So how to get particular value from this array
i have tried echo $abc->name
and echo $abc->id
but not access
Solution 1:[1]
You can just do this:
echo $memus[0]['name'];
Or if you want all of them
foreach ($memus as $memu) {
echo $memu['name'];
}
Solution 2:[2]
The arrow ($object->property)
notation is for objects.
The notation for accessing array elements is $array[$index][$key]
.
So in your case, to access the name key in your second array would be:
echo($menu[1]['name'])
, in your example this would echo the string 'zxcvxc'.
Solution 3:[3]
You can use collections in laravel 5
collect($arrayName);
$filtered = $arrayName->where('parent', 0);
$filtered->all();
Hope this will help. If not please let me know.
Solution 4:[4]
To get a particular value
{{memus[0]->id}}
Solution 5:[5]
If you want to access some array's data just do
$array_name[index]->key
in the controller or in the view.
Index is usually an integer and the key is what you are looking to extract.
For instance, we would do this on your array: $menu_zero = $menus[0]->id;
it would give us 13 and $menu_name_zero = $menu[0]->name;
would give the name.
Solution 6:[6]
You can do it this way:
For single item you can do this:
echo ($menus[0]['parent'] == 0) ? $menus[0]['name'] : '';
With foreach
loop:
foreach ($menus as $menu) {
if($menu['parent'] == 0){
echo $menu['name'];
}
}
Solution 7:[7]
Use this line for me worked
$memus = Menu::where('parent', 0)->get()->toArray();
$arr = array();
foreach ($memus as $s) {
array_push($arr,$s->buy_product_id)
}
Solution 8:[8]
Query :: $firstCategory = ProductCategory::select('id')->offset(0)->limit(1)->get()->toArray();
How to display value :: $firstCategory[0]['id'];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Laurence |
Solution 2 | Joe |
Solution 3 | Kapil Verma |
Solution 4 | HDJEMAI |
Solution 5 | JJJ |
Solution 6 | Niamul |
Solution 7 | Rahman Rezaee |
Solution 8 | Vishal Parmar |