2

I am working with a JSON dataset provided via CSV file from my client. I have processed the CSV into a JSON format.

I have the following result (dataset reduced from 1304 to 2 for readability)

"1": {
    "title": "Abercarn RFC",
    "address": "High Street, Abercarn, Newport, Gwent",
    "postcode": "NP11 5GQ",
    "category": "Club",
    "website": "http://abercarn.rfc.wales",
},

"2": {
    "title": "Abercarn RFC",
    "address": "High Street, Abercarn, Newport, Gwent",
    "postcode": "NP11 5GQ",
    "category": "Seniors",
    "website": "http://abercarn.rfc.wales",
}

I want to be able to loop through my array (pre-json_encode($array)) and merge these objects but preserve both the category values into a CSV list, so the ideal output in this case will be

"category": "Club, Seniors"

I am happy to simply merge all the other fields as they are consistently the same across the data set.

dWinder
  • 11,597
  • 3
  • 24
  • 39
WebDevDanno
  • 1,122
  • 2
  • 22
  • 50

1 Answers1

2

You can do it with simple loop (I used the title to define similarity between element but you can change that):

$arr = array(["title" => "Abercarn RFC", "category"=> "Club"], ["title" => "other title", "category"=> "BlaBla"], ["title" => "Abercarn RFC", "category"=> "Seniors"]);

$res = array();
foreach($arr as $e) {
    if (isset($res[$e["title"]]))
        $res[$e["title"]]["category"] .=   ", " . $e["category"];
    else $res[$e["title"]] = $e;
}

If you want to remove the array key you can use array_values.

$res will be your desire output.

dWinder
  • 11,597
  • 3
  • 24
  • 39