Shafayet Nur Alam
Shafayet Nur Alam

Reputation: 21

Convert string into a 2d array by splitting on two delimiters

I need to separate a string value on @ , then explode those values by ,. enter image description here

$str = '1000,10.00,10000.00@500,5.00,2500.0';


$ex = explode('@',$str);
 //result = Array ( [0] => 1000,10.00,10000.00 [1] => 500,5.00,2500.00 );
 
$ex2 = explode(',',$ex);
//result need Array ( [0] => 1000, [1] => 500, [2] => 2500);

Upvotes: 0

Views: 56

Answers (2)

Ahmed Hekal
Ahmed Hekal

Reputation: 478

You can use this method:

<?php
$str = '1000,10.00,10000.00@500,5.00,2500.0';
$arrayResult = [];
$arrayData = explode('@',$str);
foreach($arrayData as $sing){
    $arrayResult[] = explode(",",$sing);
}

echo "<pre>";
print_r($arrayResult);
echo "</pre>";

Upvotes: 1

user8034901
user8034901

Reputation:

explode() returns an array, so $ex will be an array that you need to iterate/foreach over:

<?php
// Init array to hold exploded values
$exploded = [];
$str = '1000,10.00,10000.00@500,5.00,2500.0';

$ex = explode('@',$str);

// Iterate over the $ex-exploded items
foreach ( $ex as $exItem ) {
  // Add items to the $exploded array
  array_push($exploded, explode(',', $exItem));    
}

print_r($exploded);

will output

Array
(
    [0] => Array
        (
            [0] => 1000
            [1] => 10.00
            [2] => 10000.00
        )

    [1] => Array
        (
            [0] => 500
            [1] => 5.00
            [2] => 2500.0
        )

)

Edit: If you want all values in one array you could

$exploded = array_merge($exploded[0], $exploded[1]);
print_r($exploded);

which will output

Array
(
    [0] => 1000
    [1] => 10.00
    [2] => 10000.00
    [3] => 500
    [4] => 5.00
    [5] => 2500.0
)

Upvotes: 0

Related Questions