0

I have a string that looks like the below:

Name,Age,Location
Jo,28,London

How would I convert this into an associative array so it reads like this:

Array
(
    [Name] => Jo
    [Age] => 28
    [Location] => London
)

I've tried to explode the string and manipulate it that way but got nowhere fast ($body = explode(',', $body);) I tried to use array_map() but it expected an array in the first place.

I've looked through a few articles (PHP CSV to Associative Array with Row Headings) but again they are using array_map().

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
pee2pee
  • 3,619
  • 7
  • 52
  • 133
  • 1
    The CSV solution should be more then enough. Do not get stuck on small things like this. You simply get the first row from the results. https://php.net/manual/en/function.str-getcsv.php#117692 – szab.kel Sep 03 '18 at 08:59

4 Answers4

6

You are trying to over-engineer simple thing, which result in wasting too much time for having task done.

$str = "Name,Age,Location\nJo,28,London";

$lines = explode("\n", $str);
$keys = explode(',', $lines[0]);
$vals = explode(',', $lines[1]);

$result = array_combine($keys, $vals);

But even ordinary loop would do the trick in your case and this is what you should end up with unless you had better ideas:

$result = []; 
for($i=0; $i<count($keys); $i++) {
   $result[$keys[$i]] = $vals[$i];
}

I also recommend getting thru list of available built-in array functions for future benefits.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
  • 1
    I tried something similar but the string had leading line breaks so doing a trim() on it sorted it - thank you – pee2pee Sep 03 '18 at 09:06
1

This answer will handle multilined CSV files.

Array_shift will take the first line and make that the keys, then loop the rest of the lines and use the keys in array_combine.

$str = "Name,Age,Location
Jo,28,London
Do,35,London";

$arr= explode("\n", $str);
$keys = explode(",",array_shift($arr));
foreach($arr as $line){
    $new[]= array_combine($keys, explode(",", $line));
}

var_dump($new);

https://3v4l.org/hAmCN

array(2) {
  [0]=>
  array(3) {
    ["Name"]=>
    string(2) "Jo"
    ["Age"]=>
    string(2) "28"
    ["Location"]=>
    string(6) "London"
  }
  [1]=>
  array(3) {
    ["Name"]=>
    string(2) "Do"
    ["Age"]=>
    string(2) "35"
    ["Location"]=>
    string(6) "London"
  }
}
Andreas
  • 23,610
  • 6
  • 30
  • 62
0

you try this code:

$ex = explode(PHP_EOL, $string)
$arr = array_combine(explode(',',$ex[0]), explode(',',$ex[1]));
print_r($arr);die;
Quan Lee
  • 146
  • 4
0

Try this, it's working:

  $content = $string;
  $delimiter = ",";
  $enclosure = '"';
  $escape = "\\" ;
  $rows = array_filter(explode(PHP_EOL, $content));
  $header = NULL;
  $data = [];

  foreach($rows as $row)
  {
    $row = str_getcsv ($row, $delimiter, $enclosure , $escape);

    if(!$header) {
      $header = $row;
    } else {
      $data[] = array_combine($header, $row);
    }
  }