This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 8 years ago.
I'm transposing some db results for statistic generation.
Original array:
Array
(
[0] => Array
(
[a] => apple
[b] => beer
[c] => chocolate
)
[1] => Array
(
[a] => aardvark
[b] => bear
[c] => chupacabra
)
)
Desired result:
Array
(
[a] => Array
(
[0] => apple
[1] => aardvark
)
[b] => Array
(
[0] => beer
[1] => bear
)
[c] => Array
(
[0] => chocolate
[1] => chupacabra
)
)
Sample code:
$stats[] = array(
'a' => 'apple',
'b' => 'beer',
'c' => 'chocolate'
);
$stats[] = array(
'a' => 'aardvark',
'b' => 'bear',
'c' => 'chupacabra'
);
foreach (array_keys($stats[0]) as $key){
$data[$key] = array_column($stats, $key);
}
The above code is working fine using array_keys and array_column (php 5.5).
Is there a more elegant way or php function to achieve the same result?
What is the common name for this kind of re-factoring?
EDIT:
As per comments below the correct term for this is "transposing"
I had thought there was an array_* function for that sort of thing, but I couldn't remember so I went to the PHP documentation Turns out that array_merge_recursive does just what you want.
array_merge_recursive($array1, $array2)
You have your arrays to combine in a single array, so you'll have to populate the function's arguments with the contents of the array.
call_user_func_array("array_merge_recursive", $stats)
That one line should do what you are looking for.
Related
This question already has answers here:
php check if value exsist in array, in another array
(4 answers)
Closed 4 years ago.
I have an array $check which has codes associated to offer and basket - both of these have key values. I would like to check if the values in basket are present in offer.
Scenario 1, this would fail because basket does not contain DEF:
Array
(
[offer] => Array
(
[0] => 'ABC',
[1] => 'DEF',
),
[basket] => Array
(
[0] => 'ABC',
[1] => '123',
[2] => '456',
)
)
Scenario 2, this would pass because basket array contains both ABC and DEF
Array
(
[offer] => Array
(
[0] => 'ABC',
[1] => 'DEF',
),
[basket] => Array
(
[0] => 'ABC',
[1] => 'DEF',
[2] => '123',
)
)
What's the most effective way to compare the arrays?
As you showed no effort in solving your problem, make effort in understanding this):
echo count($check['offer']) == count(array_intersect($check['basket'], $check['offer'])) ? 'All present' : 'Nope';
After an exhausting search I found some similar problems like the one I would like to solve, but I could not use their answers.
Hier are some very good examples:
How to remove duplicate values from a multi-dimensional array in PHP
How to remove duplicate values from a multi-dimensional array in PHP
How to remove duplicate values from a multi-dimensional array in PHP revisited
This one is the most similar, but the answer somehow doesn't work to me.
php filter array values and remove duplicates from multi dimensional array
The main difference to my issue is that while people are looking for a solution to delete an entire duplicated subarray from the array, I'm trying to delete the subarray when only one $key => $value pair of the subarray is similar to the correspondent pair of another subarray. The other pairs could have different values or even the same.
Here my array:
Array(
[0] => Array
(
[0] => AAA
[1] => 500
)
[1] => Array //Won't be delete 'cause [0] is different, although [1] is the same.
(
[0] => BBB
[1] => 500
)
[2] => Array //Will be delete 'cause [0] is the same.
(
[0] => AAA
[1] => 500
)
[3] => Array //Won't be delete 'cause [0] is different.
(
[0] => CCC
[1] => 820
)
[4] => Array
(
[0] => AAA //Will be delete 'cause [0] is the same. [1] is also different.
[1] => 774
)
How could I manage to delete these subarrays so I have following result:
Array(
[0] => Array
(
[0] => AAA
[1] => 500
)
[1] => Array
(
[0] => BBB
[1] => 500
)
[2] => Array
(
[0] => CCC
[1] => 820
)
Many thanks in advance!
The easiest solution (in my opinion), instead of using magical array_filter and array_map handicraft which is difficult to maintain, is to write a specialized function yourself:
$out = [];
$usedKeys = [];
foreach ($in as $element)
{
list ($a, $b) = $element;
if (!isset($usedKeys[$a]))
{
$usedKeys[$a] = true;
$out[]= $element;
}
}
var_dump($out);
This will return only elements whose first pair element is unique (taking first one, if multiple entries are available).
This works for me (based on the link provided):
<?php
$items = array(
array(
0 => 'AAA',
1 => 500,
),
array(
0 => 'BBB',
1 => 500,
),
array(
0 => 'AAA',
1 => 500,
),
array(
0 => 'CCC',
1 => 820,
),
array(
0 => 'AAA',
1 => 774,
),
);
$taken = array();
foreach($items as $key => $item) {
if(!in_array($item[0], $taken)) {
$taken[] = $item[0];
} else {
unset($items[$key]);
}
}
echo '<pre>'.print_r($items,true).'</pre>';
fiddle link
Hi I have below multidimensional arrays -
Array
(
[user_attempts] => 0
[2] => Array
(
[0] => 1
[1] => 4
)
[3] => Array
(
[0] => 32
[1] => 23
)
[4] => Array
(
[0] => asdsa
)
[1] => Array
(
[0] => Earth
)
)
and my second array is like below
Array
(
[1] => Array
(
[0] => Earth
)
[2] => Array
(
[0] => 2
[1] => 3
)
[3] => Array
(
[0] => 32
[1] => 23
)
[4] => Array
(
[0] => asdsa
[1] => asdas
)
)
I need to intersect both multidimensional arrays - so the result would be
Array
(
[1] => Array
(
[0] => Earth
)
[3] => Array
(
[0] => 32
[1] => 23
)
)
Can anyone help me to sort this out.
What I have tried is using array_intersect() but it limits to single array not multidimensional i guess.
PHP comes with a ton of functions already built in, but sometimes you still have to implement things yourself. What you want to do can be easily done by using the existing functions.
The goal is to do the following steps:
Find the keys that exist in both arrays
Loop through the array using these keys
Take the items of both input arrays with each of these keys
Calculate the intersection of those two arrays
Put it into a result array
Here is one way to do this:
function array_intersect_2dim (array $a1, array $a2) {
$keys = array_intersect(array_keys($a1), array_keys($a2));
$return = array();
foreach ($keys as $key) {
$return[$key] = array_intersect($a1[$key], $a2[$key]);
if (sizeof($return[$key]) == 0) {
unset($return[$key]);
}
}
return $return;
}
It works only for two dimensions. If you need more, you have to build a recursive approach, which follows the exact same principle.
To make the easier to compare you can use serialize/unserialize on this one. And then use array_intersect(). Try this example: Sample Output
$array1 = array( 'user_attemps' => 0, 2 => array(1, 4), 3 => array(32, 23), 4 => array('asdsa'), 1 => array('Earth'),);
$array2 = array( 1 => array('Earth'), 2 => array(2, 3), 3 => array(32, 23), 4 => array('asdsa', 'asdas'),);
$result = array_map('unserialize',array_intersect(array_map('serialize', $array1), array_map('serialize', $array2)));
print_r($result);
This question already has answers here:
Combine arrays in PHP [duplicate]
(4 answers)
Closed 10 months ago.
I want to merge array in php. I have array like this:
Array ( [0] => 6 [1] => 3 [2] => 15 )
Array ( [0] => IMAGE [1] => TICKER [2] => FULL_SCREEN_VIDEO )
Array ( [0] => 434 [1] => 423 [2] => 123 )
And I want result like:
Array( [0] => 6 [1] => IMAGE [2] => 434)
Array( [0] => 3 [1] => TICKER [2] => 423)
Array( [0] => 15 [1] => FULL_SCREEN_IMAGE [2] => 123)
What will be the easiest solution for this kind of problem?
Thanks..
You want to "transpose" an array. Assuming you have these 3 arrays in an array, you can do this:
$array = array(
array(6, 3, 15),
array('IMAGE', 'TICKER', 'FILL_SCREEN_VIDEO'),
array(434, 423, 123)
);
array_unshift($array, null);
$array = call_user_func_array("array_map", $array);
If your arrays are actually 3 separate arrays, then you could just simply do this:
$array = array_map(null, $array1, $array2, $array3);
That's basically what call_user_func_array is doing.
This question already has answers here:
Compare 2-dimensional data sets based on a specified second level value
(9 answers)
Closed last year.
I have two arrays that have identical keys. I want to check array a against array b and return the the whole row of the array of a that is NOT in b. I am messing with all of them and can't get the desired results.
my arrays look like this:
//array a
Array
(
[0] => Array
(
[pid] => 457633
[name] => Test
[descr] => sample
[creator] =>
[datetime] =>
)
)
//array b
Array
(
[0] => Array
(
[pid] => 1234
[name] => server
[descr] => server
[creator] => server
[datetime] => server
)
[1] => Array
(
[pid] => 12343
[name] => serv3er
[descr] => ser3ver
[creator] => se3rver
[datetime] => serve3r
)
)
this is the result of when i array_diff_assoc(b, a)
Array
(
[1] => Array
(
[pid] => 12343
[name] => serv3er
[descr] => ser3ver
[creator] => se3rver
[datetime] => serve3r
)
)
but when i compare a to b it is blank.
I would even like to go further only compare the first value of the array (pid in this case), and if its not in both return that a row
Check out the second answer here: array_diff() with multidimensional arrays. ( just about the only variation you haven't tried ;-) )
Using array_udiff (http://us2.php.net/array_udiff) seems like the best solution.
This is the difference between these two functions : array_diff | array_diff_assoc
you can compare the results to understand
$a1 = array("a" => "red", "b" => 22, "c" => "blue", "d" => "yellow");
$a2 = array("e" => "red", "b" => 33, "g" => "blue");
$result = array_diff($a1, $a2);
print_r($result);
/* Output:
Array
(
[b] => 22
[d] => yellow
)*/
echo "\n";
echo "\n";
$result = array_diff_assoc($a1, $a2);
print_r($result);
/*
Array
(
[a] => red
[b] => 22
[c] => blue
[d] => yellow
)
*/
check in the link : https://onecompiler.com/php/3xu58w6mx
More explanations
The array_diff_assoc() function is used to compare an array against another array and returns the difference. Unlike array_diff() the array keys are also used in the comparison. The first array which will be compared with other arrays. Compared with the first array.