Marces Schn
Marces Schn

Reputation: 13

PHP add String to multidimensional Array, comma seperated

I'm trying to add a string to a 3*x Array. I have a string as an input with 150*3 values.

<?php
$myString = "5.1,3.5,Red,4.9,3,Blue,4.7,3.2,Red,4.6,3.1,Red,5,3.6,Red," //and so on   

?>

the result should look like

Array
(
    [0] => Array
        (
            [0] => 5.1
            [1] => 3.5
            [2] => Red
        )

    [1] => Array
        (
            [0] => 4.9
            [1] => 3
            [2] => Blue
        )
//and so on

)

Upvotes: 0

Views: 134

Answers (2)

mchljams
mchljams

Reputation: 441

First, you will need to convert the comma separated string into an array. Then you can use the array_chunk() function.

$myString = "5.1,3.5,Red,4.9,3,Blue,4.7,3.2,Red,4.6,3.1,Red,5,3.6,Red";

$explodedStringToArray = explode(',', $myString);
$chunked_array = array_chunk($explodedStringToArray, 3);
print_r($chunked_array);

This will produce:

Array
(
    [0] => Array
        (
            [0] => 5.1
            [1] => 3.5
            [2] => Red
        )

    [1] => Array
        (
            [0] => 4.9
            [1] => 3
            [2] => Blue
        )

    [2] => Array
        (
            [0] => 4.7
            [1] => 3.2
            [2] => Red
        )

    [3] => Array
        (
            [0] => 4.6
            [1] => 3.1
            [2] => Red
        )

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

)

Upvotes: 2

ROOT
ROOT

Reputation: 11622

You can use explode() on the string, and then use array_chunk() to chunk the array we have from explode function, keep in mind to check for the chunk size

working snippet: https://3v4l.org/qD1t0

<?php
$myString = "5.1,3.5,Red,4.9,3,Blue,4.7,3.2,Red,4.6,3.1,Red,5,3.6,Red"; //and so on 
$arr = explode(",", $myString);
$chunks = array_chunk($Arr, 3);

print_r($chunks);

Upvotes: 1

Related Questions