Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating associative array from linear array in PHP

Tags:

arrays

php

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
)
like image 587
Andrew Avatar asked Dec 21 '22 19:12

Andrew


1 Answers

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.

like image 143
Andrew Avatar answered Dec 31 '22 19:12

Andrew