0

I have an array with nested arrays inside that I need to convert into a string with a given format.

This is for a PHP website. I get the information from a database, it comes as an array, and I need to pass it to charts.js so that I can plot it.

This is the varDump I get when I query the DB:

array(4) { [0]=> array(2) { ["date"]=> string(19) "2019-05-19 00:00:00" ["price"]=> string(3) "120" } [1]=> array(2) { ["date"]=> string(19) "2019-05-12 00:00:00" ["price"]=> string(3) "100" } [2]=> array(2) { ["date"]=> string(19) "2019-05-05 00:00:00" ["price"]=> string(3) "120" } [3]=> array(2) { ["date"]=> string(19) "2019-04-28 00:00:00" ["price"]=> string(3) "110" } }

This is what I would need as a result in a text string:

data: [{
    x: 2019-05-19 00:00:00,
    y: 120
}, {
    t: 2019-05-12 00:00:00,
    y: 100
}, {
    t: 2019-05-05 00:00:00,
    y: 120
}, {
    t: 2019-04-28 00:00:00,
    y: 110
}]

2 Answers 2

2

You can use array_map as below,

$temp = array_map(function ($item) {return array_combine(["x", "y"], $item); }, $temp);

I created ['x','y'] to combine as key as replacement for $item's keys.

array_combine — Creates an array by using one array for keys and another for its values

Working demo.

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

1 Comment

Check now. I give explanation.
1

Just loop through the array and make a new one, and then json_encode it.

$data = [];
foreach ($rows as $row) {
    $data['x'] = $row['date'];
    $data['y'] = $row['price'];
}

json_encode($data);

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.