1

I got this string that I'm getting from a table in mysql

$my_string = 40-10-10,41-20-20,42-30-30;

And i'm using this to explode it

$my_array = explode(',', $my_string); and with print_r I get this:

  Array
(
    [0] => 40-10-10
    [1] => 41-20-20
    [2] => 42-30-30
)

Now I would like to get every element of that array into another arrays, for example:

[0] => 40-10-10 should be an array like this

    Array
(
 [0] => 40
 [1] => 10
 [2] => 10
)

And then those values into variables

$v1 = 40;
$v2 = 10;
$v3 = 10;

And do the same to rest of elements an arrays, I'm stuck and I do not have idea how to achieve this, I need some help, thanks.

2
  • you'd need another explode/foreach inside your main foreach, then. Commented Jun 13, 2016 at 18:38
  • explode() again but just leave them in the array and don't worry about individual vars. Commented Jun 13, 2016 at 18:48

3 Answers 3

1
$my_array = explode(',', $my_string);

and then

 $my_array2 = explode('-', $my_array[0]);

$v1 = $my_array2[0];
$v2 = $my_array2[1]:
$v3 = $my_array2[2]

or like suggest by E_p

list($v1 , $v2, $v3) =  explode('-', $my_array[0]);

and repearm for the other index of $my_array (eventually with a foreach)

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

Comments

0
$my_string = 40-10-10,41-20-20,42-30-30;
$my_array = explode(',', $my_string);

$i = 1;
foreach($my_array as $m) {
    $my_numbers = explode('-', $my_string);
    foreach($my_numbers as $number) {
        ${"v".$i} = $number;
        $i++;
    }
}

Now you can do $v1, $v2, ...

Comments

0

You could try this one using array_map function which is less code for and more readable.

$my_array = explode(',', $my_string);

function get_array($str){

  return explode('-', $str);

}

$result = array_map('get_array', $my_array);

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.