0

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

)
3
  • 1
    what have you tried, then? What went wrong? Commented May 18, 2020 at 17:18
  • I'm pretty new to PHP. I think I should use two for-loops and I need a method that gets the separation.. but how can I tell the program to take substrings until he hits a comma? And should I work with pointers or should I just erase the substring that I just used? Commented May 18, 2020 at 17:22
  • You should attempt posting some code, even if it doesn't work. Commented May 18, 2020 at 18:28

2 Answers 2

2

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
        )

)
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.