Suppose I have a a collection like this :
Collection {#447
#items: array:3 [
0 => array:6 [
"pos" => "0"
"col" => "1"
"row" => "1"
"size_x" => "2"
"size_y" => "1"
"cat_id" => "1"
]
1 => array:6 [
"pos" => "0"
"col" => "3"
"row" => "1"
"size_x" => "1"
"size_y" => "1"
"cat_id" => "11"
]
2 => array:6 [
"pos" => "0"
"col" => "1"
"row" => "2"
"size_x" => "2"
"size_y" => "1"
"cat_id" => "10"
]
]
}
Now I want an array like this that get only cat_id indexes.
[1,11,10]
How can I do that in laravel ?
There are a few ways you can do that. The easiest is to use the pluck method:
$collection->pluck('cat_id');
This will return a new Collection. If you want to convert it to an array just use toArray() or all() afterwards:
$items = $collection->pluck('cat_id')->toArray();
$collection->pluck("cat_id")->toArray();
Use pluck method and pass field name as an argument:
$new_collection = $your_collection->pluck('cat_id');
Related
I am trying to create string associated with an object and create an array. Instead of having 0 => array:1, 1 =>array:1, 2 =>array:1. I want to have just "orange" => Option {}, "mango" => Option{}, "banana" => Option {} in an array as Array:5
array:5 [▼
0 => array:1 [▼
"orange" => Option {#76 ▼
-name: "american orange"
-botanical: "citrus"
-year: "1"
-color: "orange"
-size: "2"
-scope: "season"
-choices: []
}
]
1 => array:1 [▼
"Mango" => Option {#3098 ▼
-name: "american orange"
-botanical: ""
-year: "2"
-color: "green"
-size: "4"
-scope: "season"
-choices: []
}
]
2 => array:1 [▼
"banana" => Option {#3099 ▼
-name: "Billy"
-botanical: ""
-year: "1"
-color: "dark"
-size: "2"
-scope: "season"
-choices: array:5 [▼
"" => ""
"status" => "hard"
"condition" => "ripe"
"thickness" => "thick"
"long" => "long"
]
}
]
]
This is my code, $options[] = [$resultKey => $option]; This is where i am getting it wrong. [$resultKey => $option] is the one creating an array. All I want is $resultKey => $option so that I can achieve "Orange" => Option{}. I tried $options[] = (object)[$resultKey => $option]; it is still displaying indices. as I only want pair values without indices. ["Orange" => Option{}, "Mango" => Option{}, "Banana" => Option{} ]
$options = [];
foreach ($result as $resultKey => $resultValue) {
$option = new Option($resultKey['scope'], $resultValue['name'], '', $resultValue['botanical'], $resultValue['year'], $resultValue['color'], $resultValue['size'] !== 'choice' ? [] :$num[0]);
$options[] = [$resultKey => $option];
// dump([$resultKey => $option]);
}
```
I am passing below data through API in postman.
I want to access these values from collection inside array for Items.
{
"user":"abc",
"supplier":"xyz",
"pdate":"1",
"items":[
{
"product":"Apple",
"qty":"1",
"rate":"40",
"amount":"40"
},
{
"product":"Banana",
"qty":"6",
"rate":"4",
"amount":"24"
}
]
}
Do you mean that you want to conver the items into Collection? If that's the case, you can do:
$data = json_decode('{ "user":"abc", "supplier":"xyz", "pdate":"1", "items":[ { "product":"Apple", "qty":"1", "rate":"40", "amount":"40" }, { "product":"Banana", "qty":"6", "rate":"4", "amount":"24" } ] }', true, 512, JSON_THROW_ON_ERROR);
$items = collect($data['items']);
dd($items);
This will output:
Illuminate\Support\Collection {#1545
#items: array:2 [
0 => array:4 [
"product" => "Apple"
"qty" => "1"
"rate" => "40"
"amount" => "40"
]
1 => array:4 [
"product" => "Banana"
"qty" => "6"
"rate" => "4"
"amount" => "24"
]
]
}
Please note, I have just added and json_decoded the data, for the sake of the example, but just do this in your controller where the data is passed in.
This question already has answers here:
Sorting Laravel Collection via Array of ID's
(3 answers)
Closed last year.
Suppose I have a collection like this named categories :
Collection {#447
#items: array:3 [
0 => array:6 [
"pos" => "0"
"col" => "1"
"row" => "1"
"size_x" => "2"
"size_y" => "1"
"cat_id" => "1"
]
1 => array:6 [
"pos" => "0"
"col" => "3"
"row" => "1"
"size_x" => "1"
"size_y" => "1"
"cat_id" => "11"
]
2 => array:6 [
"pos" => "0"
"col" => "1"
"row" => "2"
"size_x" => "2"
"size_y" => "1"
"cat_id" => "10"
]
]
}
On the other hand there is an array of IDs like this :
[11,10,1]
Now I want to sort element of that collection based on their cat_id index as sorted in an array. means I want result array to be like this :
Collection {#447
#items: array:3 [
0 => array:6 [
"pos" => "0"
"col" => "3"
"row" => "1"
"size_x" => "1"
"size_y" => "1"
"cat_id" => "11"
]
1 => array:6 [
"pos" => "0"
"col" => "1"
"row" => "2"
"size_x" => "2"
"size_y" => "1"
"cat_id" => "10"
]
2 =>array:6 [
"pos" => "0"
"col" => "1"
"row" => "1"
"size_x" => "2"
"size_y" => "1"
"cat_id" => "1"
]
]
}
I used below codes but does not work properly:
$grids_arr = [11,10,1];
$categories = $categories->sortBy(function ($model) use ($grids_arr) {
return array_search($model->cat_id, $grids_arr);
});
Update :
This is my completed Code I'm using:
$categories = Category::isTile()->get();
$grids = collect(config('settings.data_grids'));// This is an array of IDs
if ($grids->isNotEmpty()) {
$grids_arr = $grids->pluck("cat_id")->toArray();
$grids_arr = array_map('intval', $grids_arr); //convert string array elements to integer
$categories = $categories->sortBy(function ($catg) use ($grids_arr) {
return array_search($catg->cat_id, $grids_arr);
});
}
You probably have not responded because of differences between config('settings.data_grids') And $categories. So edit your code as follows
Please add these three lines to your code:
$catIds = $categories->pluck('cat_id')->toArray(); //get all cat_id
$diff = array_diff($catIds, $grids_arr); // difference array from query
$grids_arr = array_merge($grids_arr , $diff); //merge difference with array
for example:
$categories = Category::select('*')->get(); //for example
$array = [
[
"pos" => "0",
"col" => "1",
"row" => "1",
"size_x" => "2",
"size_y" => "1",
"cat_id" => 1,
],
[
"pos" => "0",
"col" => "1",
"row" => "2",
"size_x" => "2",
"size_y" => "1",
"cat_id" => 10,
]
];
$grids = collect($array);
if ($grids->isNotEmpty()) {
$grids_arr = $grids->pluck("cat_id")->toArray();
$grids_arr = array_map('intval', $grids_arr);
//Please add these three lines to your code
$catIds = $categories->pluck('cat_id')->toArray();
$diff = array_diff($catIds, $grids_arr);
$grids_arr = array_merge($grids_arr, $diff);
//-----
$sorted = $categories->sortBy(function ($model) use ($grids_arr) {
return array_search($model->cat_id, $grids_arr);
});
return $sorted->values()->all();
}
please check the code below.
$array = [
0 => [
"pos" => "0",
"col" => "3",
"row" => "1",
"size_x" => "1",
"size_y" => "1",
"cat_id" => "11",
],
1 => [
"pos" => "0",
"col" => "1",
"row" => "2",
"size_x" => "2",
"size_y" => "1",
"cat_id" => "10",
],
2 => [
"pos" => "0",
"col" => "1",
"row" => "1",
"size_x" => "2",
"size_y" => "1",
"cat_id" => "1",
],
];
$array = array_reverse(array_sort($array, function ($value)
{
return $value['cat_id'];
}));
dd($array);
Hope that it helps you.
I have an array with some data that returns me from the database, the problem is that not all the keys are associated, I should fill the missing keys with data to 0.
My array is by default is:
array:1 [▼
9 => array:2 [▼
4 => array:3 [▼
"Orange" => array:3 [▼
"price" => "600.00"
"total" => "690.00"
]
"Apple" => array:3 [▼
"price" => "650.00"
"total" => "870.00"
]
"Banana" => array:3 [▼
"price" => "50"
"total" => "40"
]
]
21 => array:1 [▼
"Apple" => array:3 [▼
"price" => "44"
"total" => "33"
]
]
]
]
The array should have the same structure but with data at 0
Result:
array:1 [▼
9 => array:2 [▼
4 => array:3 [▼
"Orange" => array:2 [▼
"price" => "600.00"
"total" => "690.00"
]
"Apple" => array:2 [▼
"price" => "650.00"
"total" => "870.00"
]
"Banana" => array:2 [▼
"price" => "50"
"total" => "40"
]
]
21 => array:3 [▼
"Apple" => array:2 [▼
"price" => "44"
"total" => "33"
],
"Orange" => array:2 [▼
"price" => "0"
"total" => "0"
],
"Banana" => array:2 [▼
"price" => "0"
"total" => "0"
]
]
]
]
The "for" below modify each array with adding any new value and also avoid duplicate values. Basically, it finds the differences and then merge that, setting the first array to clone each array.
$fruits = array (
1 => array('Manzana', 'Naranja', 'Pera'),
2 => array('Pera', 'Sandia'),
3 => array('Manzana', 'Melocotones')
);
print_r($fruits);
for ($i = 1; $i <= count($fruits)-1; $i++) {
$result = array_diff($fruits[1], $fruits[1+$i]);
$merge = array_merge($fruits[1+$i], $result);
$fruits[1+$i] = $merge;
$fruits[1] = $merge;
}
print_r($fruits);
?>
Here to see how run it!
https://repl.it/KqUi/3
If you will always use the first element as boilerplate you can do something like this:
$boilerplate = reset($array);
array_walk_recursive($boilerplate, function (&$value) {
$value = 0;
});
$array = array_map(function ($items) use ($boilerplate) {
return array_merge($items, array_diff_key($boilerplate, $items));
}, $array);
Here is working demo.
I have a php array something like this:
array:7 [▼
"id" => 13
"agent_id" => 1
"reserved_by" => 1
"vehicle_type" => "["Bus","Car"]"
"no_of_vehicle" => "["2","1"]"
"created_at" => "2017-06-13 05:46:49"
"updated_at" => "2017-06-13 05:46:49"
]
Here, vehicle_type and no_of_vehicle are in json_encode format. In the above case,
By json_decode I can get two arrays like this
vehicle_type
dd(json_decode($data->vehicle_type));
array:2 [▼
0 => "Bus"
1 => "Car"
]
no_of_vehicle
dd(json_decode($data->no_of_vehicle));
array:2 [▼
0 => "2"
1 => "1"
]
Now, what I want is to create an associative array of vehicle type and number equals 1.
array:3 [▼
Bus => "1"
Bus => "1"
Car => "1"
]
It's impossible as all you say because of unique key. But, Is to possible to make similar array with nested like:
array:3 [▼
array:1 [▼
Bus => "1"
]
array:1 [▼
Bus => "1"
]
array:1 [▼
Bus => "1"
]
]
That will be fine for me
Any idea, I am using laravel 5.3
Thanks
array:3 [▼
Bus => "1"
Bus => "1"
Car => "1"
]
It's impossible, because the keys must unique
you can make it to
["Bus", "Bus", "Car"]
or
["Bus" => 2, "Car" => 1]
Answer to updated question
You can do like this:
$array = [
"id" => 13,
"agent_id" => 1,
"reserved_by" => 1,
"vehicle_type" => array("Bus", "Car"),
"no_of_vehicle" => array("2", "1"),
"created_at" => "2017-06-13 05:46:49",
"updated_at" => "2017-06-13 05:46:49",
];
$result = [];
foreach ($array["vehicle_type"] as $key => $vehicle) {
$num = intval($array["no_of_vehicle"][$key]);
for ($i = 1; $i <= $num; $i++) {
$result[] = array($vehicle => "1");
}
}
the $result will be:
array:3 [▼
0 => array:1 [▼
"Bus" => "1"
]
1 => array:1 [▼
"Bus" => "1"
]
2 => array:1 [▼
"Car" => "1"
]
]
I would create an array like that :
array[
{
vehicle_type => 'Bus',
no_of_vehicle => 2,
},
{
vehicle_type => 'Car',
no_of_vehicle => 1,
}
]
or
array['Bus_1', 'Bus_2', 'Car_1']