pee2pee
pee2pee

Reputation: 3802

Convert two-line csv string (header and values) to associative array

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().

Upvotes: 0

Views: 11774

Answers (4)

Ahmad Al- Hashlamoun
Ahmad Al- Hashlamoun

Reputation: 143

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);
    }
  }

Upvotes: 0

Andreas
Andreas

Reputation: 23958

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"
  }
}

Upvotes: 1

Marcin Orlowski
Marcin Orlowski

Reputation: 75645

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.

Upvotes: 6

Quan Lee
Quan Lee

Reputation: 146

you try this code:

$ex = explode(PHP_EOL, $string)
$arr = array_combine(explode(',',$ex[0]), explode(',',$ex[1]));
print_r($arr);die;

Upvotes: 0

Related Questions