I want to combine my ordered products and display the order list.
Controller :
$orders = Order::where('customer_id', 1)->pluck('products');
print_r($orders);
This is what I receive:
Array (
[0] =>
[
{"id":3,"product_id":3,"size":"47","quantity":7,"name":"Simple Regular T-shirt","price":2200,"thumbnail":"Thumbnail_614291597.jpg"},
{"id":7,"product_id":4,"size":"47","quantity":8,"name":"Simple Regular Shirt","price":123,"thumbnail":"Thumbnail_91520734.jpg"}
]
[1] =>
[
{"id":9,"product_id":3,"size":"45","quantity":2,"name":"Simple Regular T-shirt","price":2200,"thumbnail":"Thumbnail_614291597.jpg"}
]
)
But I want.
Array (
[0] =>
[
{"id":3,"product_id":3,"size":"47","quantity":7,"name":"Simple Regular T-shirt","price":2200,"thumbnail":"Thumbnail_614291597.jpg"},
{"id":7,"product_id":4,"size":"47","quantity":8,"name":"Simple Regular Shirt","price":123,"thumbnail":"Thumbnail_91520734.jpg"},
{"id":9,"product_id":3,"size":"45","quantity":2,"name":"Simple Regular T-shirt","price":2200,"thumbnail":"Thumbnail_614291597.jpg"}
]
)
How I can do this?
I already tried a different way, but I can't do this. Firstly I was trying to convert it array and then use the array_marge() function for those arrays. but that array needs only two arrays but for my case, it is not specified how many arrays the user has given. And try to solve it with a loop (I just tried). I am new in this field.
You could try
$orders = Order::where('customer_id', 1)
->pluck('products')
->values()
->flatten(1);
The pluck will return a collection, flatten with a depth of 1 will remove the nesting. values will reset the keys to sequential - (it's not strictly necessary here)
Laravel Docs - Collections - Values
Laravel Docs - Collections - Flatten
Just add flatten() after applying the query (with ->get()):
$orders = Order::where('customer_id', 1)->get()->pluck('products')->flatten();
print_r($orders);
Side note:
Instead of print_r() You can use dump() to pretty print the output in your browser
$orders->dump(); //only dump
$orders->dd(); //dump and exit
Related
The situation is as follows. I have a parent array which looks like the following:
$parent = [
1 => ['test1', 'test2'],
2 => ['test1_1', 'test2_2'],
];
I would like to group the data by column.
Desired result:
[
1 => ['test1', 'test1_1'],
2 => ['test2', 'test2_2'],
]
1 parent array called parent contains 2 arrays inside. I want to combine these two so that they have the same values as stated above. So this would mean that the arrays should be combined based on index number.
Since I do not make use of string keys, how would I accomplish this? I believe that there is no build in function available for this situation.
I would imagine that I could start beginning to create a new array and use a for loop through the parent array.
I tried the array-combine function however, this is NOT displaying the results I want.
[
1 => ['test1' => 'test1_1', 'test2' => 'test2_2'
]
If you need to preserve those first level keys, you can re-apply them after tranposing.
Code: (Demo)
var_export(
array_combine(array_keys($parent), array_map(null, ...$parent))
);
Otherwise, you can just transpose and accept the re-indexed first level keys. Honestly, I can't see any good reason to preserve the first level keys because by transposing, you remove the initial association between first level keys and the row values.
Code: (Demo)
var_export(
array_map(null, ...$parent)
);
If these techniques do not suit your actual project data, then we will need a more realistic sample array to be provided in your question body.
Loop over the keys of the top-level array. Then use the current index of the iteration to get the corresponding columns of the nested arrays.
$result = [];
foreach (array_keys($parent) as $i => $k) {
$result[$k] = array_column($parent, $i);
}
DEMO
This assumes the number of rows is the same as the number of columns. It's not clear what you expect the result to be if that's not true.
I am newly php developer, i have worked on codeigniter project, get data from database below
Array(
[0]=>(
[id]=>1,
[no_of_services]=>guide,assistant
),
[services]=>(
[id]=>1,,
[quote_id]=>1,
[tour_reference]=>GD/Amsterdam/2019
))
But i need to required below this:
Array(
[0]=>(
[id]=>1,
[no_of_services]=>guide,assistant,
[services]=>(
[id]=>1,,
[quote_id]=>1,
[tour_reference]=>GD/Amsterdam/2019
)
),
)
Please help me how to array of inner array function
Thanks Regards
It seems that you are not processing the data retrieved from database, correctly.
We could help you more, only if you provide your code snippet here.
However you can transform your array by using following steps:
1) Initialize a new empty array named $output
2) Iterate your database result array in a 'for' loop
3) In 'for' loop, do operations to insert in $output array as per your desired format.
4) In the end, $output array is your desired array.
I have an array as follows:
$aq=['jonathan','paul','andy','rachel'];
Then I have an array as follows:
$bq=['rachel','andy','jonathan'];
What I need is to use the ordering of the first array to sort my second array.
So for this instance, the resulting sorted array should be:
$cq=['jonathan','andy','rachel'];
I started working on a solution that uses the highest key as the top value (the head of the array) because what Im looking for is the top value but that ran into issues and seemed more like a hack so i think sorting is what im looking for.
Is there a simple function in php that can sort my data based on my first array and there respective positions in the array
please try this short and clean solution using array_intersect:
$aq = ['jonathan','paul','andy','rachel'];
$bq = ['rachel','andy','jonathan'];
$cq = array_intersect($aq, $bq);
var_export($cq);
the output will be :
array ( 0 => 'jonathan', 2 => 'andy', 3 => 'rachel', )
You'll have to use a custom sort function. Here we grab the keys of corresponding entries in the "ordering" array and use them to order the working array.
In this example, we give up (return 0) if the key doesn't exist in the ordering array; you may wish to customize that behavior, but this should give you the general idea.
$order = ['jonathan','paul','andy','rachel'];
$arrayToSort =['rachel','andy','jonathan'];
usort($arrayToSort,function($a,$b) use ($order){
if( ! array_key_exists($a,$order) ) return 0;
if( ! array_key_exists($b,$order) ) return 0;
if( array_search($a,$order) > array_search($b,$order)
return 1;
return -1;
});
I have a laravel collection object.
I want to use the nth model within it.
How do I access it?
Edit:
I cannot find a suitable method in the laravel documentation. I could iterate the collection in a foreach loop and break when the nth item is found:
foreach($collection as $key => $object)
{
if($key == $nth) {break;}
}
// $object is now the nth one
But this seems messy.
A cleaner way would be to perform the above loop once and create a simple array containing all the objects in the collection. But this seems like unnecessary duplication.
In the laravel collection class documentation, there is a fetch method but I think this fetches an object from the collection matching a primary key, rather than the nth one in the collection.
Seeing as Illuminate\Support\Collection implements ArrayAccess, you should be able to simply use square-bracket notation, ie
$collection[$nth]
This calls offsetGet internally which you can also use
$collection->offsetGet($nth)
and finally, you can use the get method which allows for an optional default value
$collection->get($nth)
// or
$collection->get($nth, 'some default value')
#Phil's answer doesn't quite obtain the nth element, since the keys may be unordered. If you've got an eloquent collection from a db query it'll work fine, but if your keys aren't sequential then you'll need to do something different.
$collection = collect([0 => 'bish', 2 => 'bash']); $collection[1] // Undefined index
Instead we can do $collection->values()[1] // string(4) bash
which uses array_values()
Or even make a macro to do this:
Collection::macro('nthElement', function($offset, $default = null) {
return $this->values()->get($offset, $default);
}):
Example macro usage:
$collection = collect([0 => 'bish', 2 => 'bash']);
$collection->nthElement(1) // string(4) 'bash'
$collection->nthElement(3) // undefined index
$collection->nthElement(3, 'bosh') // string (4) bosh
I am late to this question, but I thought this might be a useful solution for someone.
Collections have the slice method with the following parameters:
$items->slice(whereToStartSlice, sizeOfSlice);
Therefore, if you set the whereToStartSlice parameter at the nth item and the sizeOfSlice to 1 you retrieve the nth item.
Example:
$nthItem = $items->slice($nth,1);
If you are having problems with the collection keeping the indices after sorting... you can make a new collection out of the values of that collection and try accessing the newly indexed collection like you would expect:
e.g. Get the second highest priced item in a collection
$items = collect(
[
"1" => ["name" => "baseball", "price" => 5],
"2" => ["name"=> "bat", "price" => 15],
"3" => ["name" => "glove", "price" => 10]
]
);
collect($items->sortByDesc("price")->values())[1]["name"];
// Result: glove
Similar to morphs answer but not the same. Simply using values() after a sort will not give you the expected results because the indices remain coupled to each item.
Credit to #howtomakeaturn for this solution on the Laravel Github:
https://github.com/laravel/framework/issues/1335
Assume the following association among three tables in a database:
//working with three tables a client 'has one' business
//and a business has many business hours.
The following would give us an array of Activerecord objects:
$this->client->business->businesshours
and we would have to pull an object form the array to get its column value:
$this->client->business->businesshours[0]->start_time
Since I am new to PHP Activerecord, what are some ways of proceeding to pull/sort/use information from an array of objects other than looping with a foreach() loop? Are there methods to sort through the array of objects, pull information based on a column value, any best practices?
There is not a library-specific practice for sorting or pulling certain businesshour objects out of the result array. If you want to manipulate the returned array of objects you need to use standard PHP array functions like array_map on the result array.
If you know the sort order or the conditions you want for the returned objects in the result array you should instead specify these in your association declaration so you don't return objects that you don't want or need.
Since you haven't posted any code you'll just have to extrapolate to your own situation from this example:
static $has_many = array(
array(
'businesshours',
'conditions' => array('hour BETWEEN ? AND ?' => array(9, 17)),
'order' => 'hour ASC'
)
);
This association declaration will return only the businesshour objects between 9 and 17 and do it in ascending order. So as you can see, if you constrain your associations to only the records you need, there will be no need to sort or parse the result array once received.
Sometimes it's useful to use array_map to get only certain objects from your result array:
// get $result array
$new = array_map(function($obj) { if ($obj->hour > 9){ return $obj; } }, $result);