How to access the array inside the array - php

I don't know why I can't figure this out.
In my controller, how can I loop through this array and only get the values for name and url.
both of those values will be passed to insert a new record.
array:3 [▼
0 => array:2 [▼
"name" => "Discogs"
"url" => "https://www.discogs.com/artist/267549"
]
1 => "2"
2 => array:2 [▼
"name" => "Official homepage"
"url" => "http://www.blackmetal.com/~mega/TBD/"
]
]

You can do with this code:
foreach ($array as $value) {
if (is_array($value) && isset($value['name']) && isset($value['url'])) {
// Do whatever you want
}
}

You can try utilising Laravel's collection for this...
$items = collect($array)
->filter(function($item) {
return is_array($item);
});
If you have extra attributes to the ones you listed then you can use map() to for this:
$items = collect($array)
->filter(function($item) {
return is_array($item);
})
->map(function($item) {
return Arr::only($item, [
'name',
'url',
];
});
p.s. don't forget to add use Illuminate\Support\Arr; to use Arr

Related

Laravel 7 Illegal offset type

I am having an error when I try to when updating multiple names of filters.
public function update(Request $request, Filter $filter)
{
$filters = collect([$request->filters]);
$filters->each(function ($item) use ($request, $filter) {
if (!isset($item['name']) && !isset($item['latin'])) {
foreach ($item as $key) {
$data = [
'category_id' => $request->category_id,
'name' => $item[$key]['name'],
'latin' => $item[$key]['latin'],
'field' => $item[$key]['field'],
];
$filter->update($data);
}
} else {
return ;
}
}
}
When I change this, the first record is updated.
'name' => $item[1]['name'],
'latin' => $item[1]['latin'],
'field' => $item[1]['field'],
I now had three records and I changed all three folds and hit the reserve. The first record changed, the second and the third did not change. I want it to be n.
When I try this
$filters->each(function ($item) use ($request, $filter) {
if (!isset($item['field'])) {
dd($item);
}
I see this message
array:2 [▼
5 => array:4 [▼
"name" => "Value RAM"
"latin" => "ram"
"field" => "0"
"value" => array:2 [▼
0 => "One Gigabayte"
1 => "Twoo Gigabayte"
]
]
6 => array:3 [▼
"name" => "Color"
"latin" => "color"
"field" => "1"
]
]
#irankhostravi you are trying to get the wrong key from the array:
You are calling 'latin' => $item[$key]['latin'] but $key is not an integer but the value, because you are looping too many times trough the array.
If I dump the output of the $key this is what I get:
array:3 [▼
"latin" => "ram"
"field" => "0"
"value" => array:2 [▶]
]
// dump($key)
"key: ram"
So you need to remove that extra foreach(), which isn't necessary.
Besides of that, your are checking if 'name' and 'latin' are not set, if so, then you try to get the value of these non-existing keys..
I've refactored some of your code and I think this is what you need:
public function update(Request $request, Filter $filter)
{
collect($request->filters)
->each(function ($item) use ($request, $filter) {
// Check if the keys exists in the $item, otherwise return.
// Changed && to || because if one of them is missing, you want to abort,
// unless your database is accepting empty/nullable values.
// But please use validation rules here instead: https://laravel.com/docs/master/validation#quick-writing-the-validation-logic
if (! isset($item['name']) || ! isset($item['latin']) || ! isset($item['field'])) {
return;
}
$filter->update([
'category_id' => $request->category_id,
'name' => $item['name'],
'latin' => $item['latin'],
'field' => $item['field'],
]);
});
}

Sql query where table is connected to it self and create a array using php

I have 1 table name page_live. Now I want to display it if isMenu = 1. Now it is connected to it self with filed name parent_Id.
As an example -
I have page_live named test_page and this row is a parent of a row named inside-1. And inside-1 is parent of inside-2.
Now, I have to create array which will look like -
[0]=>{
'name' => 'test_page'
[0]=> {
'name' => 'inside-1'
[0] => {
'name' => 'inside-2'
}
}
}
This is my table -
Model PageLive
<?php
namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
class PageLive extends Model
{
protected $table = 'page_live';
protected $fillable = ['name', 'adminId', 'slugName', 'description',
'imageId', 'metaTitle', 'metaDesc', 'metaKeyword', 'pageTypeId', 'parent_id',
'isHome', 'pageDraftId', 'themeLayoutId'];
public function parent()
{
return $this->belongsTo(App\Http\Models\PageLive::class, 'parent_id');
}
public function children()
{
return $this->hasMany(App\Http\Models\PageLive::class, 'parent_id');
}
}
Please help me.
Thank you.
You Need to use recursive relations in your Model:
public function childrenPages()
{
return $this->hasMany(PageLive::class, 'parent_id', 'id');
}
public function allChildrenPages()
{
return $this->childrenPages()->with('allChildrenPages');
}
Then in Controller:
$page = PageLive::with('allChildrenPages')->first();
$page->allChildrenPages; // collection of recursively loaded children
// each of them having the same collection of children:
$page->allChildrenPages->first()->allChildrenPages; // .. and so on
I can't guarantee it will be efficient for your data, I tried to give you the idea and part of the code, you need to test it definitely.
You can use recursive function to achieve this.
public function abc( $ar, $pid = null ) {
$op = array();
foreach( $ar as $item ) {
if( $item['parent_id'] == $pid ) {
$op[$item['id']] = $item;
// using recursion
$children = $this->abc( $ar, $item['id'] );
if( $children ) {
$op[$item['id']]['children'] = $children;
}
}
}
return $op;
}
Use function something like this and call it wherever you want.
You will get array structure like -
array:1 [▼
1 => array:5 [▼
"id" => 1
"name" => "Test Page"
"slugName" => "test-page"
"parent_id" => null
"children" => array:1 [▼
3 => array:5 [▼
"id" => 3
"name" => "Inside 1"
"slugName" => "test-page2"
"parent_id" => "1"
"children" => array:1 [▼
4 => array:4 [▼
"id" => 4
"name" => "Inside 2"
"slugName" => "test-page3"
"parent_id" => "3"
]
]
]
]
]
]
Hope this will help you.

How to select multiple columns with pluck() from selection in laravel

The probleme is that when dd($responsablle or $type) its shows only first_name
i need to select first_name and id
public function create(){
$responsable = User::all()->pluck('first_name','id');
$type = EventType::all()->pluck('type','id');
return view ('backend.event.create', compact('responsable', 'type'));
}
First use pluck on the Builder instead of retrieving all the records with all their fields then plucking the fields from the Collection:
$responsable = User::pluck('first_name', 'id');
$type = EventType::pluck('type', 'id');
The second arguement is the field you want to key the Collection/array by. The id part is the key of the element:
foreach ($responsable as $key => $value) {
// $key is the 'id' field
// $value is the 'first_name'
}
foreach ($type as $key => $value) {
// $key is the 'id' field
// $value is the 'type'
}
Or to be more useful with the naming:
foreach ($responsable as $id => $first_name) { ... }
foreach ($type as $id => $type) { ... }
Laravel 5.8 Docs - Query Builder - Retrieving Results - Retrieving A List Of Column Values pluck
Laravel 5.8 Docs - Collections - Available Methods - pluck pluck
To be honest, you don't actually have to use pluck() here. If you simply limit the columns being returned via ->select(), you will receive records with their attributes limited to the columns specified:
$users = User::select('first_name', 'id')->get();
$types = EventType::select('type', 'id')->get();
Now, when looping over these, you'll have access to first_name, id and type, id:
foreach($users AS $user){
echo $user->id."|".$user->first_name;
}
foreach($types AS $type){
echo $type->type."|".$type->id;
}
Note, this does return the full Model for User and EventType, but casting to an array will condense that to just an associative array for each record:
$users = User::select('first_name', 'id')->get()->toArray();
dd($users);
/* array:2 [▼
0 => array:2 [▼
"first_name" => "Bob"
"id" => "1"
]
1 => array:2 [▼
"first_name" => "Mike"
"id" => "2"
]
] */
$types = EventType::select('type', 'id')->get()->toArray();
dd($types);
/* array:2 [▼
0 => array:2 [▼
"type" => "Red"
"id" => "1"
]
1 => array:2 [▼
"type" => "Blue"
"id" => "2"
]
] */
Then, when looping, you can access similarly:
foreach($users AS $user){
echo $user["id"]."|".$user["first_name"];
}
// Or, $users[0]["first_name"], etc.
foreach($types AS $type){
echo $type["type"]."|".$type["id"];
}
// Or, $types[0]["type"], etc.

delete an array in list array in laravel session

I have a session to save cart info in laravel like this:
$item = [
'id' => 1,
'product_id' => 11
];
$item2 = [
'id' => 2,
'product_id' => 22
];
\Session::push('cart', $item);
\Session::push('cart', $item2);
Now I want delete an Item in array for $id=1:
foreach(\Session::get('cart') as $cart)
{
if($id==$cart['id'])
{
echo 'done';
\Session::forget('cart.' . $i);
}
$i++;
}
It print done but it can not delete that item in list.
what is my wrong?
also I try \Session::pull('card.id', $id);
EDIT
with dd(\Session::get('cart'))
array:4 [▼
2 => array:5 [▼
"id" => 1
"product_id" => "11"
]
3 => array:5 [▶]
4 => array:5 [▶]
5 => array:5 [▶]
]
So I try change the code to this:
foreach(\Session::get('cart') as $key->$cart)
{
if($id==$cart['id'])
{
\Session::forget('cart.' . $key);
}
}
But It can not delete too
I'm pretty sure that cart.{$id} is not a session key, as you're only explicitly setting cart, which is an array. This should work for you instead:
$id = 1; // set from request, etc.
$cartSession = session()->get("cart");
foreach($cartSession AS $index => $cart){
if($index == $id){
unset($cartSession[$index]);
}
}
session()->put("cart", $cartSession);
Essentially, you pull the session to a variable (array), loop that and unset where $index matches $id, then set the remaining array back as "cart".
Note: I'm using session() instead of \Session, which is just Facade vs global function; shouldn't make a difference on which you use, unless below a certain Laravel version (< 5.0 I believe)

Add key and value to array if it doesnt exist

So I have an Array called $sales that consits of objects like:
"DR22" => array:3 [▼
"brand" => "DR22"
"year" => "0"
"last_year" => null
]
"FGIPA46C" => array:3 [▼
"brand" => "FGIPA46C"
"month" => "3"
"year" => "3"
]
Now each one should have "Month" "Year" "Last Year" "Last Month" but if there is no sale its not in there, which i get, but if it doesnt exist I just want to add it with 0 value. I tried:
foreach ($sales as $sale)
{
if (empty($sale['month'])) {
$sale['month'] = 0;
}
}
But it doesnt add anything. Spits out the same.
foreach ($sales as &$sale) {if (empty($sale['month'])) { $sale['month'] = 0; }}
You need to pass the $sale array by reference (using the &). This will mean that the original $sales array is updated
Or you can use array_map function, for example:
$array = array_map(function($item){
if(empty($item["month"])){
$item["month"] = 0;
}
return $item;
}, $array);

Categories