Making Javascript array with PHP

576

Solution:

You can use this

// declare an array
$json_array = array();
while ($row2 = mysqli_fetch_array($result2)) {
        // add this code
        $json_array[] = array(
            "{$row2['Straat']}",
            "{$row2['Noorderbreedte']}",
            "{$row2['Westerlengte']}",
            $row2['ID']
        );
        //echo '[' . $row2['Straat'] . ',' . $row2['Noorderbreedte'] . ',' . $row2['Westerlengte'] . ',' . $row2['ID'] . '],';
    }
?>
<script type="text/javascript">
var locations = <?php echo json_encode($json_array);?>
395

Answer

Solution:

There's no need to invent a wheel.json_encode function will do what you need:

PHP:

$locations = array();
while ($row2 = mysqli_fetch_array($result2)) {
    $locations[] = array(
        $row2['Straat'],
        $row2['Noorderbreedte'], 
        $row2['Westerlengte'],
        $row2['ID']
    );
}

JS:

var locations = <? echo json_encode($locations)?>;

People are also looking for solutions to the problem: php - cakephp join query is not working

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.