Merged with Cartesian Product of N arrays.
I need to get all combinations of array.
Example:
array
(
array("a","b"),
array("1","2","3","4")
);
And i need to get
array
(
array("a","1"),
array("a","2"),
array("a","3"),
array("a","4"),
array("b","1"),
array("b","2"),
array("b","3"),
array("b","4"),
);
Of course it must work when sizeof($array) >= 2.
Thanks much
Related
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
Basically,I want to sort an array based on another array.
As in,
<?php
$movies=array("Avengers","Spiderman","Batman","Flash");
$ratings=array(9,3,4,7,);
?>
In other words,the $movies[0]("Avengers") has a ratings of 9 , $movies[1]("Spiderman") has a rating of 3 and so on.
I want the ratings array to be sorted numerically in descending order and thus sorting the movies array.I will like this to be in a function.
Thus, the array will be thus:
<?php
$movies=array("Spiderman","Batman","Flash","Avengers",);
$ratings=array(3,4,7,9);
?>
The ratings array has been sorted and thus the movies array has also been sorted but according to the ratings array.
I am sorry I am a newbie in php and I know that doing that is probably very simple but I don't know how to do It.The only way I can think of is using inserting into an sql table then selecting from it in descending order but that will probably be a very bad idea.....
Any help is highly appreciated. Thanks in advance.
Oh and if it is easier to do it in Laravel (I use laravel) please show me how
You can use array_combine() to combine movie names and ratings.
So, that movie names will be the keys of resulting array and ratings will be the values.
Now, sort using arsort() so that the new array will be sorted in descending order by ratings keeping movie names as it is.
Print the array.
Code:
<?php
$movies=array("Spiderman","Batman","Flash","Avengers",);
$ratings=array(3,4,7,9);
$movieRatings = array_combine($movies, $ratings);
arsort($movieRatings);
echo '<pre>';print_r($movieRatings);
?>
Output:
Array
(
[Avengers] => 9
[Flash] => 7
[Batman] => 4
[Spiderman] => 3
)
try this,
array_combine ( array $keys , array $values ) : array
it works by setting the values in one array as keys of another array which in your case is your movies.
<?php
$movies=array("Avengers","Spiderman","Batman","Flash");
$ratings=array(9,3,4,7,);
$result = array_combine ( $movies, $ratings);
// then sort this way...
arsort($result, 0);
?>
documentation for both functions are here...
https://www.php.net/manual/en/function.array-combine.php
https://www.w3schools.com/php/func_array_arsort.asp
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 got two arrays. Array A with Soccer-Player positions and array B with Soccer-Players.
Every Player got a name and a position.
Now I wanted to split array B in the different postions of array A and re-order it in one array sorted like the positions in array A.
The arrays look like this:
Array A
Array ( tor,
abwehr,
mittelfeld,
sturm )
Array B
Array ( Array ( Rocky, Sturm ),
Array ( Kevin, Abwehr ) )
My result array should look like this:
Array ( tor,
abwehr(Array ( Kevin, Abwehr )),
mittelfeld,
sturm(Array ( Rocky, Sturm )) )
My code till now:
$positionen = array("tor", "abwehr", "mittelfeld", "sturm");
foreach($positionen as $position) {
$team = $extern_source->api();
foreach($team['data'] as $team) {
//need to explode this to filter relevant infos
$team_info = explode("\n",$team['info']);
$sp_name=$team_info[1];
$sp_posi=$team_info[4];
//put together the single infos in a new array
...
I really hope you understand my problem.
It put knots in my brain. so complicated :D
Thank you very much!
Best regards from Germany.
foreach($arrayB as $player){
$position[$player[1]][] = $player[0];
}
First prepare the final array before the first foreach:
$data = array_fill_keys($positionen, array());
Then after feching the name and the position, do this:
$data[$sp_posi][] = $sp_name;
Note: array_fill_keys requires PHP 5.2 or higher
I'm trying to systematically loop through 2 arrays, and match their values for some quick processing. Let me set up my specific situation:
Array 1
productID,
companyID,
name,
price
Array 2
companyID,
name,
rebate1,
rebate2
I want to loop through Array 1, and when the companyID matches an ID inside of Array 2, I will do some quick math based on the rebate1, rebate2 values for that companyID.
Right now I am looping through Array 1, and then on EACH item in Array 1 I loop through the entire Array 2 to see if the companyID exists. I know this can't be the fastest/cleanest solution...
EDIT
The key values for Array 1 look like:
$array1[0]['productID']
$array1[0]['companyID'] (etc...)
$array1[1]['productID']
$array1[1]['companyID'] (etc...)
The key values for Array 2 look like:
$array2[0]['companyID']
$array2[0]['rebate1'] (etc...)
$array2[1]['companyID']
$array2[1]['rebate1'] (etc...)
Use the companyId as key for Array 2, i.e., make sure that
$Array2[$Array1[$i]['companyID']]['companyID'] == $Array1[$i]['companyID']
This gives you constant time lookup of companies in Array 2 based on companyID and you can do your calculation with
$Array2[$Array1[$i]['companyID']]['rebate1']`
and
$Array2[$Array1[$i]['companyID']]['rebate2']`
Example:
foreach ($Array1 as $value) {
if (isset($Array2[$value['companyID']])) {
//TODO: use $Array2[$value['companyID']] for calculation
} else {
// TODO: handle case companyID not in $Array2
}
}
What approximate sizes do you expect for each of your arrays?
While as you say, your method isn't certainly the fastest (looks like 0(n²)), below 10'000 elements in each array I doubt you can see any significant speed difference.
If you have 150'000 in array1 and 200'000 in array2, that's a whole other story and you'll have to look for an algorithm that is rather 0(log n).
Edit:
As mentioned above, let's just make your array associative if you can:
Instead of:
Array2 = array(
0 => array(
'Company_id' => 'Hello',
'rebate_1' => '50%',
)
);
Make it:
Array2 = array(
'Hello' => array(
'rebate_1' => '50%',
)
);
And then use:
if (isset(array2[$company_id]))
{
// do your stuff
}
If you can't modify Array2's structure where it's coming from, you should transform it on the fly in your search function's scope, so that it looks like above, and then use the transformed array. Transforming Array2 into an associative one shouldn't take too long, for the number of elements you say you have.
The easiest way I can think of is to use the companyID as the key for Array 2:
$companies[$companyID]=array($name,$rebate1,$rebate2)
and then you just reference it directly looping Array 1
$products[$x]=array($productID,$companyID,$name,$price);
...
$newprice1=$products[$x][3]/$companies[$products[$x][1]][1];
$newprice2=$products[$x][3]/$companies[$products[$x][1]][2];
My answer is slightly different from the first one, mind the arrays...
You can create a new array indexed by the company id as follows:
$cid = array_map(function($a) {return $a['companyID'];}, $array2);
$new2 = array_combine($cid, $array2);
With that, you can loop through the first array and access the data:
foreach ($array1 as $key => $value){
$rebate1 = $new2[$value['companyID']]['rebate1'];
$rebate2 = $new2[$value['companyID']]['rebate2'];
}