1
...
$php_array = mysqli_fetch_all($result,MYSQLI_ASSOC);
?>

<script type='text/javascript'>
<?php
$js_array = json_encode($php_array);
echo "var location = ". $js_array . ";\n";
?>
</script>   

How can I modify the above code that gives me this output (an array of objects methinks?)

var javascript_array = [
    {"city":"Hermosa Beach","lat":"33.860069","lng":"-118.398784"},
    {"city":"San Jose","lat":"34.694628","lng":"-118.398784"},
    .... ]

to give me this... (an array of arrays?)

var javascript_array = [
    ["Hermosa Beach",33.860069,-118.398784],
    ["San Jose",34.694628",-118.398784],
    .... ]  

without a bunch of foreaching's...

2
  • 1
    check out this documentation on how to transfer between php and javascript: cullenwebservices.com/… Commented Sep 5, 2014 at 22:28
  • 1
    @jordan.peoples His question isn't how to transfer between php and JS, it's how to change the structure of his array. Commented Sep 5, 2014 at 22:45

2 Answers 2

2

Use MYSQLI_NUM instead of MYSQL_ASSOC when you call mysqli_fetch_all(). Then the rows will be indexed arrays instead of associative arrays.

Although I don't know why you would want the array to be like this. Arrays should be used for uniform data, objects should be used for heterogeneous data.

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

Comments

1

thanks, this works and is very lean...

<?php

    $query = "SELECT * FROM file";
    $result = $con->query($query);

    // Fetch all rows and return the result-set as an associative array:
    // using numeric keys for the array, instead of creating an associative array.
    $php_array = mysqli_fetch_all($result,MYSQLI_NUM);
?>  

<script type='text/javascript'>
    <?php

    // create a JSON representation of a value that javascript will understand
    $js_array = json_encode($php_array);

    // dump json object into javascript variable 'locations'
    echo "var locations =" .  $js_array . ";\n";
    ?>
</script>   

6 Comments

BTW: In JavaScript everything is an object and no it is NOT very clean
why do you say not clean?
php tag inside script tag? Really? Consider separate client code and server code. As said before, to communicate between them, use the technics that are thought for that
Lean as in lacking "unnecessary code and functionality". True that mixing PHP in javascript is not very orthodox. I will use Ajax call and that will illiminate the issue, but I was working up the model piece by piece trying understand PHP/javascript array/object interaction.
Final comment: Don't post that kind of testing code here, please. Posting your own FINAL solution to the problem is fine and even encouraged!
|

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.