Bob
Bob

Reputation: 413

Convert comma separated array to nested array with php function

I need to convert array_1 to array_2 with a PHP function. I tried many things but nothing works. I hope someone can help me out here. I think I need an each function or something to loop through the comma separated array and convert it into the array_2.

$array_1 = array (
  0 => '6801,6800,7310,6795',
);

$array_2 = array (
  0 =>
  array (
    0 => '6801',
    1 => '6800',
    2 => '7310',
    3 => '6795',
  ),
);

Upvotes: -1

Views: 95

Answers (3)

jspit
jspit

Reputation: 7693

Just create a new array with a value returned by the explode function. Reset always returns the first value of the array regardless of the key.

$array_1 = array (0 => '6801,6800,7310,6795');

$newArray = [explode(",", reset($array_1))];

Upvotes: 0

Maik Lowrey
Maik Lowrey

Reputation: 17556

Use PHP explode function. https://www.php.net/manual/de/function.explode.php

$newArray[] = explode(",", $array_1[0]);

// output

Array
(
    [0] => Array
        (
            [0] => 6801
            [1] => 6800
            [2] => 7310
            [3] => 6795
        )

)

Upvotes: 0

Nabil
Nabil

Reputation: 1278

Here a solution

<?php

$array_1 = array (
  0 => '6801,6800,7310,6795',
);


$array_2 = array();

foreach ($array_1 as $value) {

    array_push($array_2 , explode(",",$value)); 
}
               

print_r($array_2);

?>

The output that i got

Array ( [0] => Array ( [0] => 6801 [1] => 6800 [2] => 7310 [3] => 6795 ) )

Upvotes: 1

Related Questions