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
Related
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'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'];
}
I am using Cassandra and I have saved some byte representations as ID. Everything is working fine, however that data (id) is no good for output.
$users = $db->get('1');
echo '<pre>';
print_r($users);
die();
Outputs
Array
(
[��� X��W��c_ ] => Array
(
[id] => ��� X��W��c_
[name] => steve
[surname] => moss
)
[�*B�X��y�~p��~] => Array
(
[id] => �*B�X��y�~p��~
[name] => john
[surname] => doe
)
)
As you can see ID's are some wierd characters, it's because they are byte representations in database. They actually look like \xf5*B\xa0X\x00\x11\xe1\x99y\xbf~p\xbc\xd1~.
In PHPCASSA there is function CassandraUtil::import(); to which I can pass these bytes and it will return guid. It works fine, but I want my array to automatically converted from bytes to guids.
Only option I find is looping through every item in array and assigning new value to it. Somehow I think that it is not the best approach. Is there any other ways to do this?
TL;DR
Have array with bytes like above, need to use CassandraUtil::import(); on array keys and id's to get readable id's. What is the most effective way of doing so.
UPDATE
Sorry, only saw the top level array key, I think you would have to run the function below as well as another one after:
function cassImportWalkRecur(&$item, $key)
{
if ($key == 'id')
$item = CassandraUtil::import();
}
$array = array_walk_recursive($array, 'cassImportWalkRecur');
That should apply it to the ID fields. If you need to check the data first, there maybe a way to detect the encoding, but I am not sure how to do that.
You should be able to create a function and use array_walk to traverse the array and update the keys. Something like:
function cassImportWalk($item, &$key)
{
$key = CassandraUtil::import();
}
$array = array_walk($array, 'cassImportWalk');
Untested (also you may have to change the CassandraUtil usage), but should work.
Unless I am misunderstanding the question this can be done simply and cleanly like so:
$users = $db->get('1');
$keys = array_keys($users);
$readableKeys = array_map("CassandraUtil::import",$keys);
foreach($users as $currentKey => $subArray) {
$readableKey = array_shift($readableKeys);
$subArray['id'] = $readableKey;
$users[$readableKey] = $subArray;
unset($users[$currentKey]);
}
Would array_flip() all keys and values, then array_walk() and apply my function, before doing a final array_flip().
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