I am working with a web service that returns JSON data, which, when I decode with PHP's json_decode function, gives me an array like the following:
Array
(
[0] => eBook
[1] => 27
[2] => Trade Paperback
[3] => 24
[4] => Hardcover
[5] => 4
)
Is there a PHP function that will take this array and combine it into an associative array where every other element is a key and the following element is its value? What I want to come up with is the following:
Array
(
[eBook] => 27
[Trade Paperback] => 24
[Hardcover] => 4
)
As far as I know, there is no built-in function that does this, but you could use a function like the following:
function combineLinearArray( $arrayToSmush, $evenItemIsKey = true ) {
if ( ( count($arrayToSmush) % 2 ) !== 0 ) {
throw new Exception( "This array cannot be combined because it has an odd number of values" );
}
$evens = $odds = array();
// Separate even and odd values
for ($i = 0, $c = count($arrayToSmush); $i < $c; $i += 2) {
$evens[] = $arrayToSmush[$i];
$odds[] = $arrayToSmush[$i+1];
}
// Combine them and return
return ( $evenItemIsKey ) ? array_combine($evens, $odds) : array_combine($odds, $evens);
}
You can call that with the array you want to combine into an associative array and and optional flag indicating whether to use even or odd elements as the keys.
Edit: I changed the code to use only one for loop, rather than a separate loop to extract even and odd values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With