Home > Blockchain >  Change array formatting in PHP
Change array formatting in PHP

Time:09-23

I have an existing array in this following structure,

Array
     (
       [0] => 2,4
       [1] => 3,5
     )

And, I want to convert in the following structure:

Array
     (
       [0] => 2
       [1] => 4
       [2] => 3
       [3] => 5
     )

Any suggestions, please let me know.

Thanks in advance!

CodePudding user response:

Pretty easy - I assume that the 2,4 is an array and not a string yes? if so:

<?php

$array = array
     (
       0 => [2,4],
       1 => [3,5]
     );


echo '<pre>Original:<pre>';
print_r($array);

foreach($array as $val){
    foreach($val as $v){
        $newArray[] = $v;
    }
}

echo '<pre>Created:<pre>';
print_r($newArray);

Will return:

Original:
Array
(
    [0] => Array
        (
            [0] => 2
            [1] => 4
        )

    [1] => Array
        (
            [0] => 3
            [1] => 5
        )

)
Created:
Array
(
    [0] => 2
    [1] => 4
    [2] => 3
    [3] => 5
)

if you meant that the array is "2,4" string in 0 and "3,5" in 1 than:

<?php

$array = array
     (
       0 => "2,4",
       1 => "3,5"
     );


echo '<pre>Original:<pre>';
print_r($array);

foreach($array as $val){
    $V = explode(",",$val);
    foreach($V as $v){
        $newArray[] = $v;
    }
}

echo '<pre>Created:<pre>';
print_r($newArray);

will return :

Original:
Array
(
    [0] => 2,4
    [1] => 3,5
)
Created:
Array
(
    [0] => 2
    [1] => 4
    [2] => 3
    [3] => 5
)

CodePudding user response:

I'm assuming the integers in the first array are actually strings, if so the following answer should work:

$old_arr = ["2,4","3,5"];
$new_arr = [];
foreach ($old_arr as $double) {
    $nums = explode(',',$double);
    foreach ($nums as $single) {
        array_push($new_arr, intval($single));
    }
}
  • Related