Home > OS >  Explode () inside foreach loop
Explode () inside foreach loop

Time:04-06

I have this $array DD.MM.YYYY|XX,xxx

[0]=> string(17) "04.01.2021|26,140" 
[1]=> string(17) "05.01.2021|26,225" 
[2]=> string(17) "06.01.2021|26,145"

I need to create 2 more arrays from it, e.g. $array_date and $array_value.

I tried something like foreach and inside the loop use explode() function but I have no idea, I also checked some previous posts for this problem but to no avail.

CodePudding user response:

Try this way:

$data = [
    '04.01.2021|26,140',
    '05.01.2021|26,225',
    '06.01.2021|26,145'
];

function extract_array($array) {

    $result = [];

    foreach($array as $row) {       
        $values = explode("|", $row);
        $result['array_date'][] = $values[0];
        $result['array_value'][]  = $values[1];
    }

    return $result;

}

print_r(extract_array($data));

// Array
// (
//    [array_date] => Array
//        (
//            [0] => 04.01.2021
//            [1] => 05.01.2021
//            [2] => 06.01.2021
//        )
//
//    [array_value] => Array
//        (
//            [0] => 26,140
//            [1] => 26,225
//            [2] => 26,145
//        )
//
// )

CodePudding user response:

As you described, you can use explode inside a foreach and then populate the 2 arrays.

Assuming the format of all the strings are the same:

$array = [
    "04.01.2021|26,140",
    "05.01.2021|26,225",
    "06.01.2021|26,145"
];

$array_date = [];
$array_value = [];

foreach($array as $value) {
    $parts = explode('|', $value);
    $array_date[] = $parts[0];
    $array_value[] = $parts[1];
}

CodePudding user response:

This should work with list():

 $array = [
     "04.01.2021|26,140",
     "05.01.2021|26,225",
     "06.01.2021|26,145"
 ];


 $date_array = [];
 $value_array = [];
  
 foreach ( $array as $i )
 {
     list($date, $value) = explode("|",$i);
     $date_array[] = $date;
     $value_array[] = $value;
  }

CodePudding user response:

You can also use array_walk_recursive()

I would prefer having dates and values as part of the same array when accessing them. Instead of $array_date[key] and $array_value[key] you would have them in $array[key]['date'] and $array[key]['value']. But it depends on what you want to do with the result.

$data = array(
    "04.01.2021|26,140",
    "05.01.2021|26,225",
    "06.01.2021|26,145"
);

array_walk_recursive($data, function($value) use (&$result){
    $parts = explode('|', $value);
    $result[] = array(
        'date'  => $parts[0],
        'value' => $parts[1]
    );
});

print_r($result);
  • Related