Randomize array of objects which contains specific key->value - php

I have an array with 45 object elements containing id, name, is_premium.
From MySQL I receive them, ordered by is_premium desc, and some of them have is_premium = 0 at the end of list.
How can I randomize elements with is_premium=1, keeping the is_premium=0 at the end of array?

Try if this works:
<?php
//assuming the array of objects is called $array
$new_array = array_merge(
shuffle(
array_filter($array,function($x){return $x['is_premium'] == 1;})
),
array_filter($array,function($x){return $x['is_premium'] == 0;})
);
?>

Related

Restructure 2d array so that column values become row values (transpose but preserve first level keys)

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.

sort array based on other array sort

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;
});

Put a Array in another Array by comparing their values

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

Fast method for Looping through Array to match a common ID in a second array

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'];
}

sorting arrays - Sorting an array from outside data

I am attempting to make an ordered array based on an unsorted array from an SQL database.
The data that is gotten from the database will look something like this:
Array (
//array ('name', position)
array ('george', 2),
array ('lenny' , 4),
array ('rabbit', 1),
array ('pet' , 3)
)
The idea is to sort the 'names' in an array where position is there place in the array.
What I would like to to end up being:
Array ( 'rabbit', 'george', 'pet', 'lenny' )
The current way I have attempted this is using split_array()
$result is the array from the database.
foreach ( $result as $res ){
$a = array(array($res['name'], $res['position']));
array_splice($finalArray, ($res['position'] - 1), 0, $a);
}
The issue is sometimes depending on the order the users are retrieved it will not sort it properly, is there a better way to do this, or is this good and I am doing it wrong?
Thanks.
Use uasort http://php.net/manual/en/function.uasort.php function where you can pass a user defined comparasion function like this:
$myArray = array(array('bill',3),array('joe',4),array('john',1));
/**
* #desc compare two arrays by the second element
* #param array $a (array to compare with an other)
* #param array $b (array to compare with an other)
* #return int 0|1|-1 equals|first is bigger|second is bigger
*/
function myCompare($a,$b){
if( $a[1] == $b[1] ){
return 0; //if the 2nd elements equals return 0
}
return ( $a[1] > $b[1] )?1:-1; //if the 2nd element of the 1st parameters is bigger returns 1 , else returns -1
}
Usage:
uasort( $myArray, 'myCompare' );
The uasort manipolates the original array in place.
Result:
var_dump($myArray);
array(
array('john',1),
array('bill',3),
array('joe',4)
);
Recommendation:
If you could edit the SQL query , better to short the results in the query with ORDER BY directive like this:
SELECT `name`,`position`
FROM `mytable` #your table name
WHERE 1 #or your conditions here
ORDER BY `position` ASC #ordering directive
This should run faster. And if use this, recommend to add index to position field.

Categories