Can't get my head around a simple way to do this. I'm creating the end point on an API for some graph data and need to create a response that contains an array of labels and another array for the values.
I already have the array of postcodes, what I want to do I be able to have a new array that contains the postcodes grouped by the first 4 characters with a sub array of all of the postcodes of that group so I can count the array length for the values.
E.g. output:
$postcodes = ['SO30 0NG', 'SO30 OTD', 'SO31 1TG', 'RG51 5HG', 'RG51 7GH']
$grouped = [
'SO30' = [
'SO30', 'SO30'
],
'SO31' = [
'SO31'
],
'RG51' = [
'RG51', 'RG51'
]
]
My first attempt was:
foreach ($postcode as $pc) {
$cleanPostcode = str_replace(" ", "", $pc);
$cleanPostcode = substr($cleanPostcode, 0, 4);
$data[$cleanPostcode][] = $cleanPostcode;
}
But this seemed to create duplicate keys.
This works.
$postcodes = ['SO30 0NG', 'SO30 OTD', 'SO31 1TG', 'RG51 5HG', 'RG51 7GH'];
$result= array();
Foreach ($postcodes as $postcode){
$short =Substr($postcode,0,4);
// If subarray does not exist
If(!isset($result[$short])) $result[$short]=[]; //create subarray of short in result
$result[$short][]= $short; // add item in subarray
}
Var_dump($result);