Associative Array for places - php

I have 2 arrays that I have made into an Associative Array. I also have combinations of winner positions = ie '1,2', '2,3', '1,3'. What I need to do is replace the position numbers with jersey numbers and put back into the same configuration as the combinations were written. For Example, I've set up my jersey, position, combo, and associative array:
$jersey = array('3','1','5','4');
$position = array('1','2','3','4');
$AssocArr = array_combine($position, $jersey);
$Combo = array('1,2','2,3','1,3');
I've set up a function to get the values from the keys:
function getVals($finishPosMap, $keys) {
foreach($keys as $key) {
$output[] = $finishPosMap[$key];
}
return $output;
}
The part I'm having issue with is putting them back into an array with the values instead of keys. This is what I've done so far:
foreach($Combo as $set=>$pCombo) {
$com = array($set=>(explode(',', $pCombo)));
foreach($com as $set=>$com){
$c = getVals($AssocArr, $com);
print_r($c);
}
}
print_r gives me:
array( [0] => 3 [1] => 1 )
array( [0] => 1 [1] => 5 )
array( [0] => 3 [1] => 5 )
Can anyone help me put it in the format:
array(0 => '3,1', 1 => '1,5', 2 => '3,5');
Thanks in advance for your help, and please let me know if you think there'd be a better way to do this. Thanks!

I think what you're missing is the array_intersect_key(); this should do it:
$jersey = array('3','1','5','4');
$position = array('1','2','3','4');
$AssocArr = array_combine($position, $jersey);
$Combo = array('1,2','2,3','1,3');
foreach ($Combo as &$value) {
$values = explode(',', $value, 2);
$new_values = array_intersect_key($AssocArr, array_flip($values));
$value = join(',', $new_values);
}
print_r($Combo);
It updates the $Combo array in-place and for each value, calculates the intersection with your associate array.
Demo

Related

Remove duplicates from a multi-dimensional array based on 2 values

I have an array that looks like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2"),
array("Will","Smith","4")
);
In the end I want the array to look like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2")
);
The array_unique with the SORT_REGULAR flag checks for all three value. I've seen some solutions on how to remove duplicates based on one value, but I need to compare the first two values for uniqueness.
Simple solution using foreach loop and array_values function:
$arr = array(
array("John","Smith","1"), array("Bob","Barker","2"),
array("Will","Smith","2"), array("Will","Smith","4")
);
$result = [];
foreach ($arr as $v) {
$k = $v[0] . $v[1]; // considering first 2 values as a unique key
if (!isset($result[$k])) $result[$k] = $v;
}
$result = array_values($result);
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => John
[1] => Smith
[2] => 1
)
[1] => Array
(
[0] => Bob
[1] => Barker
[2] => 2
)
[2] => Array
(
[0] => Will
[1] => Smith
[2] => 2
)
)
Sample code with comments:
// array to store already existing values
$existsing = array();
// new array
$filtered = array();
foreach ($array as $item) {
// Unique key
$key = $item[0] . ' ' . $item[1];
// if key doesn't exists - add it and add item to $filtered
if (!isset($existsing[$key])) {
$existsing[$key] = 1;
$filtered[] = $item;
}
}
For fun. This will keep the last occurrence and eliminate the others:
$array = array_combine(array_map(function($v) { return $v[0].$v[1]; }, $array), $array);
Map the array and build a key from the first to entries of the sub array
Use the returned array as keys in the new array and original as the values
If you want to keep the first occurrence then just reverse the array before and after:
$array = array_reverse($array);
$array = array_reverse(array_combine(array_map(function($v) { return $v[0].$v[1]; },
$array), $array));

PHP: take out duplicate digits from an array then print them out

I'm probably [super]overthinking this. I'm trying to analyze an array with values like [1,9], [4,6] [5,5], [6,4], [9,1] and duplicate digits (I'm having a super brain fart and can't even remember the term for numbers like this) remove (the last two) so that only [1,9], [4,6] [5,5] are printed.
I was thinking that turning this array into a string and using preg_match, but I'm pretty sure this wouldn't work even if I had the correct regex.
If you have an array of pairs like this:
$x = array(
array(1,9),
array(4,6),
array(5,5),
array(6,4),
array(9,1)
);
Here is one way to get the unique pairs:
foreach ($x as $pair) {
sort($pair);
$unique_pairs[implode(',', $pair)] = $pair;
}
This uses string representations of each sorted pair as keys in a new array, so the result will have distinct values by definition.
As far as the printing them out part of your question, once you have the unique values you can loop over them and print them out in whichever format you like, for example:
foreach ($unique_pairs as $pair) { vprintf("[%d,%d]<br>", $pair); }
It looks like elements are distributed symmetrically.
We can cut the array in two halves and get only the first half with array_slice():
$array = array(
array(1,9),
array(4,6),
array(5,5),
array(6,4),
array(9,1),
);
print_r(array_slice($array, 0, ceil(count($array) / 2)));
Result:
Array(
[0] => Array(
[0] => 1
[1] => 9
)
[1] => Array(
[0] => 4
[1] => 6
)
[2] => Array(
[0] => 5
[1] => 5
)
)
Demo at Codepad.
ceil() is used to round the number up to the next highest integer if there is an even number of items in the array. Example: if there is 3 items in the array, 5 / 2 will return 2.5, we want 3 items so we use ceil(2.5) which gives 3.
Example with 3 items:
$array = array(
array(1,9),
array(5,5),
array(9,1),
);
print_r(array_slice($array, 0, ceil(count($array) / 2)));
Result:
Array(
[0] => Array(
[0] => 1
[1] => 9
)
[1] => Array(
[0] => 5
[1] => 5
)
)
Example with 4 items:
$array = array(
array(1,9),
array(7,7),
array(7,7),
array(9,1),
);
print_r(array_slice($array, 0, ceil(count($array) / 2)));
Result:
Array(
[0] => Array(
[0] => 1
[1] => 9
)
[1] => Array(
[0] => 7
[1] => 7
)
)
If I'm correct in understanding what you are trying to do, you want to remove the final 2 elements from the array?
There is a function in PHP called array_pop that removes the final element from the array.
$array = array_pop($array);
So if you run this twice, you will remove the final 2 elements from the array.
This is how I'd do it (and I hope I am not overthinking this :))
$stringArray = array();
$stringArray[] = '1,9';
$stringArray[] = '4,6';
$stringArray[] = '5,5';
$stringArray[] = '6,4';
$stringArray[] = '9,1';
foreach($stringArray as &$numString) {
$numString = explode(',', $numString);
usort($numString, function($a, $b) {return $a - $b;});
$numString = implode(',', $numString);
}
$a = array_unique($a);
print_r($a);
You basically explode every element into a subarray, sort it and then implode it back. After calling the array_unique, you're left with unique values in the array.
The output would be
Array
(
[0] => 1,9
[1] => 4,6
[2] => 5,5
)
The result you suggest treats [a,b] as equivalent to [b,a] which makes the problem a lot more complex. The code below gives the result you asked for, but without really understanding what the problem is that you are trying to fix and whether [1,9] is equivalent to [9,1] in the solution:
$a=array(array(1,9),array(4,6),...
$dup=array();
for ($i=0; $i<count($a) -1; $i++) {
for ($j=$i+1; $j<count($a); $j++) {
if (($a[$i][0]==$a[$j[0] && $a[$i][1]==$a[$j[1])
|| ($a[$i][0]==$a[$j[1] && $a[$i][1]==$a[$j[0])) {
$dup[]=$j;
}
}
}
foreach ($dup as $i) {
unset($a[$i]);
}
So I'm actually going to assume your question to have a different meaning than everyone else did. I believe what you're asking is:
How do you filter out array items where a reverse of the item has already been used?
<?php
// The example set you gave
$numberSets = [[1, 9], [4, 6], [5, 5], [6, 4], [9, 1]];
// Initialize an empty array to keep track of what we've seen
$keys = [];
// We use array filter to get rid of items we don't want
// (Notice that we use & on $keys, so that we can update the variable in the global scope)
$numberSets = array_filter($numberSets, function($set) use(&$keys) {
// Reverse the array
$set = array_reverse($set);
// Create a string of the items
$key = implode('', $set);
// Get the reverse of the numbers
$reversedKey = strrev($key);
// If the palindrome of our string was used, return false to filter
if (isset($keys[$reversedKey])) {
return false;
}
// Set the key so it's not used again
// Since $keys is being passed by reference it is updated in global scope
$keys[$key] = true;
// Return true to NOT filter this item, since it or it's reverse were not matched
return true;
});
var_dump($numberSets);

Merge keys of an array based on values

I want to merge the keys of array based on values. This is my array.
Array
(
[1] => 1
[2] => 1
[3] => 1
[4] => 2
[5] => 0
[6] => 2
[7] => 2
)
I want output as
Array
(
[1,2,3] => 1
[4,6,7] => 2
[5] => 0
)
I have been brain storming entire day but couldn't find a solution. Any hint would be much appreciated.
WHAT I HAVE TRIED:
for($i=2;$i<=count($new);$i++){
if ($new[$i-1][1]==$new[$i][1]){
$same .= $new[$i-1][0].$new[$i][0];
}
}
echo $same;
But I am stucked. I am comparing the keys one by one but it's very complicated. I don't need the code. I only need the hint or logic. Anyone kind enough?
<?php
$old_arr = ["1"=>1,"2"=>1,"3"=>1,"4"=>2,"5"=>0,"6"=>2,"7"=>2];
$tmp = array();
foreach($old_arr as $key=>$value)
{
if(in_array($value, $tmp)){
$index = array_search($value, $tmp);
unset($tmp[$index]);
$tmp[$index.",".$key] = $value;
}else{
$tmp[$key] = $value;
}
}
ksort($tmp);
echo "<pre>";
print_r($tmp);
echo "</pre>";
?>
https://eval.in/529314
You can loop through array elements and create a new array with new structure. Please check the below code it may help you
$old_array = array(1=> 1,2 => 1,
3=> 1,
4 => 2,
5 => 0,
6 => 2,
7 => 2
);
$new_array = array();
foreach($old_array as $key => $value)
{
if(in_array($value,$new_array))
{
$key_new = array_search($value, $new_array);//to get the key of element
unset($new_array[$key_new]); //remove the element
$key_new = $key_new.','.$key; //updating the key
$new_array[$key_new] = $value; //inserting new element to the key
}
else
{
$new_array[$key] = $value;
}
}
print_r($new_array);
$arr = array(1 => 1, 2 => 1, 3 => 1, 4 => 2, 5 => 0, 6 => 2, 7 => 2);
$tmp = array();
foreach ($arr as $key => $val)
$tmp[$val][] = $key;
$new = array();
foreach ($tmp as $key => $val)
$new[implode(',', $val)] = $key;
First loop the original array through, creating a temporary array, where your original values are keys and values are the original keys as an array.
Then loop the temporary array, creating the new array, where the temporary array's values are imploded as keys.
There's no way to have an array of keys to a single value, but the other way around:
function flipWithKeyArray($arr){
$result = array();
foreach($arr as $key => $val){
if(!isset($result[$val]))
$result[$val] = array();
$result[$val][] = $key;
}
return $result;
}
This will flip your array and declare one array per value of your old array and then push the keys with the same value into each list.
For an array like this:
array(1=>1, 2=>1, 3=>1, 4=>2, 5=>2, 6=>2)
The result will look like this:
array(1=>array(1,2,3), 2=>array(4,5,6))
Hope it fits your need.

Putting an array (at the end OR beginning) subarray of another array

Say I got this array:
array([0] => 0 [1] => 0 [2] => 1), how can I put this as the value of the nth key of another array, making
$array = array(
[0] => array([0] => 0 [1] => 0 [2] => 1)
)
in this example it is the 0th key of array $array
I had browsed with PHP array functions, but I got tired looking for a function that does the same thing
EDIT.
Doing: $array[0] = array(0, 0, 1); works great for first loop, but if I would like to add another array as subarray, say array(1, 1, 1), my output should be
$array = array(
[0] => array([0] => 0 [1] => 0 [2] => 1 [3] => 1 [4] => 1 [5] => 1)
)
Note that the new array, was added at the end of the last subarray.
Please help! thanks!
EDIT
$x=0;
while($x<count($WOE_CONTROL)) {
$j=0;
while($j<=30) {
if ($WOE_CONTROL[$x+3]&(1<<$j)) {
echo '<br />';
echo '<strong>'.$Castles[$j].'</strong>';
$castle_data_holder[0] = $WOE_CONTROL[$x];
$castle_data_holder[1] = $WOE_CONTROL[$x+1];
$castle_data_holder[2] = $WOE_CONTROL[$x+2];
$castle_db[$j] = $castle_data_holder;
unset ($castle_data_holder);
}
if ($x+4 < count($WOE_CONTROL)) {echo " ";}
$j=$j+1;
}
$x=$x+4;
}
Sorry, there, I am trying to extract all the data in $WOE_CONTROL which actually contains binary data, then store them temporarily to $castle_data_holder then finally, add it to $castle_db
Just set the value of $array[0] to the array. This produces a multidimensional array.
$array[0] = array(0, 0, 1);
Is this u looking for?
$array[] = array(0,0,1);
$array[] = array(1,1,1);
$array[] = array(2,2,2);
// etc...
print_r($array);
EDIT
$array[]['a1'] = array(1,1,1);
$array[]['a2'] = array(2,2,2);
$array[]['a3'] = array(3,3,3);
// etc...
print_r($array);
Finally this is u need
$a = array(1,1,1);
$b = array(2,2,2);
$c = array(3,3,3);
$value = array_merge($a,$b,$c);
print_r($value);
EDIT
$newArray = array();
foreach($yourArray as $key => $value)
{
// I say if $value is an array that u want to merge
$arrayToMerge = $value;
$newArray = array_merge($newArray,$arrayToMerge);
}
print_r($newArray);
This solved my problem:
if (empty($castle_db[$j])) {
$castle_db[$j] = $castle_data_holder;
}
else {
$castle_db[$j] = array_merge($castle_db[$j],$castle_data_holder);
}
it is going to check if the array is empty if not use merge.
Thanks everyone!

Insert value from one array to another and keep their keys

I have 2 Arrays :
Array
(
[1] => image1
[4] => image2
)
Array
(
[0] => title 1
[2] => title 2
[3] => title 3
)
I just want to merge these arrays and KEEP their key ([1] => image1 will also be at [1] in the new array)
Any idea please ? Thanks !
That should work :)
foreach ($array2 as $key => $value)
{
$array1[$key] = $value;
}
The keys & values from array2 will be appended at the end. If your array is just numeric, you can bring it to the right order with array_sort().
I think this function works. You have to use only numeric keys tough
$array1;
$array2;
array_weird_merge($array1, $array2){
$result = array();
//get the keys of each array
$keys1 = array_keys($array1);
$kesy2 = array_keys($array2);
//get the max keys of the 2 arrays
$max = max($key1, $key2);
//we go trough all the possible values
for ($i=0; $i<$max;$i++){
//if the array 1 has an element in the
//$i position, we put it in the result
//if not, then we check in the second
//array. (we give priority to the array
//that comes first)
if(isset($array1[$i])){
$result[$i] = $array1[$i];
}else if(isset($array2[$i])){
$result[$i] = $array2[$i];
}
}
return $result;
}

Categories