Skip to content
Advertisement

Pull values from string to assign into an array

I’ve got a project where I’m pulling data from SOQL using salesforce’s RestAPI. I’ve cleaned up the response and this is what I’m currently working with:

Created:2021-03-02,Tracks:1,Created:2021-02-23,Tracks:3,Created:2021-02-20,Tracks:4,Created:2021-02-16,Tracks:41,Created:2021-02-06,Tracks:1,Created:2021-02-02,Tracks:3,Created:2021-02-01,Tracks:2,Created:2021-01-29,Tracks:1,Created:2021-01-22,Tracks:1,Created:2021-01-19,Tracks:1,Created:2021-01-15,Tracks:1,Created:2021-01-14,Tracks:1,Created:2021-01-13,Tracks:1

I’m working in PHP and I’d like to build an array based off this data. For example:

graph_data = array(
          array("Created" => array("2021-03-02","2021-02-23","2021-02-20","2021-02-16")),
          array("Tracks" => array(1,3,4,41,1)));

Anyone have suggestions for this? I’ve tried doing some regex but I don’t think it’s the right solution. Originally, I got this back as an object but there’s no clean way to get them into an associative array as json_decode and json_encode did not work.

For reference, I’m building a chart based on this dynamic data and need the date created as the x axis and tracks as y axis.

Advertisement

Answer

A solution with explode() and foreach()

$arr = explode(',', $str);
$finalArray = [];


foreach($arr as $ar){
    $againExplode = explode(':',$ar);
    $finalArray[$againExplode[0]][] = $againExplode[1];
}

print_r($finalArray);

Output: https://3v4l.org/JoeJK

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement