0

I have array like this:

Array ( 
  [0] => Array ( [0] => Red [1] => Blue [2] => Black [3] => White [4] => Silver)
  [1] => Array ( [0] => Yellow [1] => Green [2] => Pink [3] => Purple)
  [2] => Array ( [0] => Orange [1] => Olive [2] => Lime)
etc..
)

Expected array:

Array ( 
   [0] => Red
   [1] => Blue
   [2] => Black
   [3] => White
   [4] => Silver
   [5] => Yellow  
   [6] => Green
   [7] => Pink
   [8] => Purple
   [9] => Orange
   [10] => Olive
   [11] => Lime
   etc..
) 

How to this refactoring? I can't understand

Thank you!

0

4 Answers 4

2

You can use the array_merge function like this...

<?php
$array1 = Array ( 
  [0] => Array ( [0] => Red [1] => Blue [2] => Black [3] => White [4] => Silver)
  [1] => Array ( [0] => Yellow [1] => Green [2] => Pink [3] => Purple)
  [2] => Array ( [0] => Orange [1] => Olive [2] => Lime)
etc..
)

$array2 = Array();
for($i=0; $i<$array1.length; $i++) {
    $array2 = array_merge($array2, $array1[$i]);
}

print_r($array2);
?>
Sign up to request clarification or add additional context in comments.

1 Comment

This solution does not work correctly. $array1.length causes an error. change it with count($array1).
1

There is a very handy built-in way in php. Array_merg is a function that will combine an unlimited number of arguments into a final array. And call_user_func_array will automatically populate the arguments into Array_merg, so we can accomplish our goal via a one-liner:

PHP

<?php

$workwith = Array ( 
    Array("Red", "Blue", "Black", "White", "Silver"),
    Array("Yellow", "Green", "Pink", "Purple"),
    Array("Orange", "Olive", "Lime")
);

$result = call_user_func_array("array_merge", $workwith);
print_r($result);

?>

Output

    Array
(
    [0] => Red
    [1] => Blue
    [2] => Black
    [3] => White
    [4] => Silver
    [5] => Yellow
    [6] => Green
    [7] => Pink
    [8] => Purple
    [9] => Orange
    [10] => Olive
    [11] => Lime
)

Comments

0

Try this

$arrayIndex = 0;
    $ar=array(
        array("red","black","blue"),
        array("Green", "Pink", "Yellow")
    );
    for ($i = 0; $i < sizeof($ar); $i++){
        for ($i1 = 0; $i1 < sizeof($ar[$i]); $i1++){
            $newArray[$arrayIndex] = $ar[$i][$i1];
            $arrayIndex++;
        }
    }

Comments

0

using array_walk_recursive

array_walk_recursive($ar, function($v, $k) use (&$list) {return $list[] = $v;});
print_r($list);

live example: https://3v4l.org/DRMKI

1 Comment

This solution is so slower than the accepted answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.