Grocker
Grocker

Reputation: 49

Php array conversion processing?

array A: array('name','world cup','lang','ru'); array B: array('name'=>'world cup','lang'=>'ru'); How to convert array A into arrayB in the best way?

Upvotes: 0

Views: 55

Answers (3)

MC1010
MC1010

Reputation: 106

If you have arrays of varying sizes, and it's always in the order of key, value, key, value, ... you can make a function that converts it:

/**
 * Converts numeric array to key - value pairs in order
 *
 * @param array $arrayA
 * @return array $arrayB
 */
function convertArrays($arrayA)
{
    $keys = array(); //array to store keys
    $values = array(); //array to store values

    //seperate keys and values
    for($i = 0; $i < count($arrayA); $i++)
    {
        if($i % 2 == 0) //is even number
        {
            array_push($keys, $arrayA[$i]); //add to keys array
        }
        else //is odd number
        {
            array_push($values, $arrayA[$i]; //add to values array
        }
    }

    $arrayB = array(); //array for combined key/value pairs

    $max = count($keys);
    if(count($keys) != count($values)) //original array wasn’t even
    {
        $max = count($keys) - 1;
    }

    //join into single array
    for($j = 0; $j < $max; $j++)
    {
        $arrayB[ $keys[$j] ] = $values[$j];
    }

    return $arrayB;
}

Upvotes: 1

Lasithe
Lasithe

Reputation: 2740

You can run a for-loop and generate the array.

While generating you need check if the next item is defined before adding it to array B.

$arrayA = array('name','world cup','lang','ru');

for($i=0; $i < count($arrayA); $i+=2){
    $arrayB[$arrayA[$i]] = isset($arrayA[$i+1]) ? $arrayA[$i+1] : '';
}

print_r($arrayB);

Upvotes: 3

Anon
Anon

Reputation: 1

if the format remains constant and you wont get more pairs:

$arrayA=array('name','world cup','lang','ru');
$arrayB=array($arrayA[0]=>$arrayA[1],$arrayA[2]=>$arrayA[3]);

print_r($arrayB);



Array
(
    [name] => world cup
    [lang] => ru

)

Upvotes: -1

Related Questions