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?
-
It’s so smart, but what if I have two elements in my array?Grocker– Grocker2018-07-19 02:44:02 +00:00Commented Jul 19, 2018 at 2:44
-
just use for loopKevin– Kevin2018-07-19 03:13:14 +00:00Commented Jul 19, 2018 at 3:13
Add a comment
|
3 Answers
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);
1 Comment
Kevin
since you're incrementing by two's you can just use isset alone, its understood that if
+1 isn't set it means its the array is jagged (missing pair), no need for modulus, something like for loop and a simple ternary $arrayB[$arrayA[$i]] = isset($arrayA[$i+1])? $arrayA[$i+1] : '';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;
}