0

I've seen other solutions on StackOverflow, but my scenario is a bit different.

I have a charts factory in PHP that receives an array of strings, for example:

$charts = ['SomeChart', 'SomeOtherChart', 'AndAnotherChart'];

and then it loops through an array, returns a new class if it exists and then runs a default method called 'run'.

foreach($charts as $key => $param) {
    try {
        if($chart = ChartsFactory::build($param)) {
            $result['charts'][$param] = $chart->run();
        }
    } catch (\Exception $e) {
        $result[$param] = $e->getMessage();
    }
}

and then I return $result;.

Inside my view, I want to pass that result to JavaScript. So I do this:

var result = <?php echo json_encode($result);?>;

It all works fine, but the only problem is that JavaScript receives an Object instead of an Array, which is not what I want because I want want to run forEach on it and some other Array related stuff.

How can I convert it to Array or make sure that it receives an Array?

1 Answer 1

2

In JavaScript, arrays can only contain numeric indexes, that's why PHP outputs an associative array with string indexes as a JavaScript object, which is the closest representation.

You can, however, iterate over a JavaScript object's properties:

for (var name in myObject) {
   // value = myObject[name]
}
Sign up to request clarification or add additional context in comments.

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.