Creating an associative array from a linear array in PHP

I am working with a web service that returns JSON data which when decoded using PHP json_decode gives me an array similar to 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 each other element is a key and the next element is its value? I want to come up with the following:

 Array ( [eBook] => 27 [Trade Paperback] => 24 [Hardcover] => 4 ) 
+4
source share
5 answers

Your own solution is understandable, but this one-liner, made only of PHP functions, does the same job:

 $output = call_user_func_array('array_combine', call_user_func_array('array_map', array_merge(array(null), array_chunk($input, 2)))); 

Your question was "is there a PHP function ...". The answer is no, but for their combination it is.

The hard part here is the transposition of the chunked array, which is achieved by calling array_map with null as the first argument (see manual for โ€œinteresting use of this function ...โ€)

+4
source

As far as I know, there is no built-in function for this, but you can use the following function:

 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 this with the array you want to combine into an associative array, and an optional flag indicating whether to use even or odd elements as keys.

Edit: I modified the code to use only one for the loop, not a separate loop for extracting even and odd values.

+5
source

Such a loop could work:

 $array = json_decode(....); $received = array(); for ($i = 0; $i < count($array); $i++) { $received[$array[$i]] = $array[$i+1]; $i++; } var_dump($received); 
+1
source

Code adjustment in another answer:

 function combineLinearArray( $arrayToSmush) { if ( ( count($arrayToSmush) % 2 ) !== 0 ) { throw new Exception( "This array cannot be combined because it has an odd number of values" ); } $combined = array(); for ($i = 0, $i<count($arrayToSmush); $i++) { $combined[$arrayToSmush[$i]] = $arrayToSmush[$i+1]; $i++; // next key } // Combine them and return return $combined; } 
+1
source

Speaking of 1 liners:

 array_reduce(array_chunk($input, 2), function(&$r, $i) { !empty($i[0]) && $r[$i[0]] = @$i[1]; return $r; }, array()); 

This 1-liner also checks the immediate validity of the received associated key and is about 10 characters less than the accepted fooobar.com/questions/1420685 / ...

0
source

All Articles