phparrayscsvassociative-arraytext-parsing

Convert lines of text containing two comma-delimited values into an associative array


I have this data set from a textarea

P234324, 2011-03-23 12:34:37 \nP234434, 2011-03-23 13:34:36 \nP438794, 2011-03-23 14:34:36 \nP238924, 2011-03-23 15:34:36 \n

I would like to explode it to this, but the multiple foreach is throwing me.

$data['P234324'] = "2011-03-23 12:34:37"
$data['P234434'] = "2011-03-23 13:34:36"
$data['P438794'] = "2011-03-23 14:34:36"
$data['P238924'] = "2011-03-23 15:34:36"

Solution

  • This will work:

    $old_data = ...; //your string
    $data = array();
    
    $pairs = explode("\n", rtrim($old_data, "\n"));
    foreach($pairs as $pair) {
       $components = explode(',', $pair);
       $data[$components[0]] = trim($components[1]);
    }
    

    codepad example