0

I am trying to append values I selected from database into an array inside foreach loop, but I don't seem to achieve much, because I only get the first value into the array and not the rest.

Here is what I have tried so far:

<?php  
include 'include/states_info.php';
header('Content-Type: application/json');

$infoObject = json_decode(stripcslashes(file_get_contents('php://input')));

if ( $infoObject->operation == 'get_all_states_info' )
{

    $statesInfo = new StatesInfo();

    $sInfoArr = $statesInfo->getAll();
    $resultObject = array();

    if ( $sInfoArr != null )
    {
        foreach ( $sInfoArr as $sInfo )
        {
            $resultObject += array(
                'coords' => array( 
                    'lat' => $sInfo['lat'], 
                    'lng' => $sInfo['lng'] 
                ),
                'name' => $sInfo['name'],
                'heat' => 0
            );
        }
    }
    
    echo json_encode($resultObject);

}
DJ MixRhymez
  • 40
  • 1
  • 9
  • 5
    Have you tried `$resultObject[] = ` – Nigel Ren Aug 12 '21 at 18:41
  • 1
    Why `stripcslashes()`? – axiac Aug 12 '21 at 18:46
  • Thank you so much, that actually worked for me – DJ MixRhymez Aug 13 '21 at 06:00
  • @axiac `stripslashes()` is from an online example of how to send `POST` data using javascript `XMLHttpRequest` – DJ MixRhymez Aug 13 '21 at 06:02
  • How old is that example? The functions `addcslashes()` and `stripcslashes()` were useful 20 years ago, before JSON became a _de facto_ standard. They are completely useless now. Use [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) in JavaScript to produce the JSON and [`json_decode()`](https://www.php.net/manual/en/function.json-decode) in PHP to get the data back. Pass `true` as the second argument to get associative arrays instead of objects. They are easier to handle in PHP. – axiac Aug 13 '21 at 09:20

0 Answers0