I have the following array:
$where = array(
'id'=>array(
12,
13,
14
),
'date'=>array(
'1999-06-12',
'2000-03-21',
'2006-09-31'
)
);
Expected output:
$comb = array(
array(12, '1999-06-12'),
array(13, '2000-03-21'),
array(14, '2006-09-31')
);
Any idea why I am not getting this expected output?
As Kris Roofe stated in his deleted answer,
array_column
is indeed a more elegant way. Just be sure to put it into some kind of aforeach
loop, similar to what Sahil Gulati showed you. For example, like this:The
var_dump
output of$result
is exactly what you're looking forWanna see a fancy trick?
(php minimum version: 5.6)
If you strip the array keys (
id
anddate
) from$where
you can use avariadic
function and write a nice tight little one-liner! And you don't have to bother instantiating anyresult
arrays -- no fuss. PHP is so excellent -- big fan.Input:
Method #1: variadic array_map() with func_get_args()
This method is robust as it will handle a variable number of "rows" and "columns". Here is a demo with a few examples.
Or if you are are sub-5.6, you can use this, but it is less flexible/robust (more literal to the OP's sample data):
Method #2: array_map() with two inputs
Output from either method:
I find
array_map()
to be my favorite function for this case because it creates the result array in the same line (as opposed to returning a true/false result like array_walk(); or using a foreach loop and printing after it is done). This means you can do a true one-liner print out without declaring a result variable...or
Solution 1: Hope this simple
foreach
to get the desired resultTry this code snippet here
Solution 2: Here we are using
array_walk
to achieve the same resultTry this code snippet here
Solution 3: Here we are using
array_shift
on$where["date"]
.Try this code snippet here