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

1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried something similar but the string had leading line breaks so doing a trim() on it sorted it - thank you
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"
  }
}

Comments

0

you try this code:

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.