0

I have this array and I need to use it in Charts

in data index I have this value [1,9] and it's coming form the comma split explode function without any quotes around it.

$main_arr = array(
        "label" => 'Total Clicks', 
        "data" => [$total_clicks], 
        "backgroundColor" => "rgba(255, 0, 0, 1)", 
    );

Then I use json_encode to turn the array into json format,

[{"label":"Total Clicks","data":["1, 9"],"backgroundColor":"rgba(255, 0, 0, 1)"}]

As you can see above there are double quotes in the square bracket, if I pass static value in the data index i.e [1, 9] it works fine. I tried regex, substring, rtrim etc but didn't work anyone. Your help would be much appreciated!

2
  • Use explode and probably trim and cast to int. Commented Apr 18, 2020 at 16:24
  • @u_mulder tried int but then it only returns first int value Commented Apr 18, 2020 at 16:26

2 Answers 2

1

You have several problems at once here. First of all your values are strings, and secondly you have an multiple values that you want to explode so you have singular values:

$total_clicks = '1, 9'; // value guessed based on unexpected output in question

$clickArray = explode(',', $total_clicks);
$clickArray = array_map('trim', $clickArray); // remove white spaces
$clickArray = array_map('intval', $clickArray); // cast everything to int
$main_arr = array(
    "label" => 'Total Clicks',
    "data" => $clickArray,
    "backgroundColor" => "rgba(255, 0, 0, 1)",
);

echo json_encode($main_arr);

this outputs:

{"label":"Total Clicks","data":[1,9],"backgroundColor":"rgba(255, 0, 0, 1)"}

For a more sloppy approach you could even skip the line where I trim the whitespaces away, as casting to integer will do this implicitly, however I like to have a clean flow of handled data.

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

Comments

1

Converting string to array of ints:

$total_clicks = "1, 9";
print_r(array_map('intval', explode(', ', $total_clicks)));

Converting string to array of strings:

$total_clicks = "1, 9";
print_r(array_map('trim', explode(', ', $total_clicks)));

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.