0

any help would be really appreciated for an educational website I'm building that stores question results. I've searched a lot on this site but not found this issue specifically.

I'm really struggling to pass SQL data using PHP to Javascript so that it ends up as a multidimensional array (with no keys) rather than an object.

I'm currently getting an object like this in JS

{"0":["y3","y2","y1","n5","y4","y6"],"1":["n5","n4","n3","y","n","y"], ...}

What I really need is an array like

[["y3","y2","y1","n5","y4","y6"],["n5","n4","n3","y","n","y"]...] 

so that I can perform other functions on it in JS (e.g. length, find index number etc).

Extract from my PHP and JS is below. I'm using echo json_encode and I've tried lots of different variations of mysqli_fetch but can't work it out. Strangely, a similar query on a different SQL table works as I'd like it to (the only difference is that it is returning lists of integers not strings).

// ...
    // Attempt to execute the prepared statement
    if(mysqli_stmt_execute($stmt)) {
        $result = mysqli_stmt_get_result($stmt);
        if(mysqli_num_rows($result) > 0) {
            //Fetch result row          
            while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                array_push($thisFact, $row["mark"]); //"mark" is the column name in the table
            }
            $progress[$x] = $thisFact; // set progress for this Fact (an array of up to 6 items)
        } // end if result > 0      
    }
    else {  
            echo "Oops! can't execute.  " ;
    }
} //end loop   
?>  

var FactProgress = <?php echo json_encode($progress); ?>;
alert(FactProgress.length);
for (var i = 0; i < FactProgress.length; i++) {

FactProgress.length shows as undefined. It then falls over on the next line when I try to use the length.

Many thanks.

4
  • You can try with JSON_PRETTY_PRINT, for example: var FactProgress = <?php echo json_encode($progress,JSON_PRETTY_PRINT); ?>; Commented Jan 5, 2020 at 22:33
  • @mickmackusa none of those duplicates explain how to deal with preserving numeric keys when the array is sparse which I believe is OPs intent based on the wording of the question. If that's not the case I will happily delete this answer. Commented Jan 6, 2020 at 7:16
  • Are you trying to preserve keys? If not please let me know so I can remove my answer. Commented Jan 6, 2020 at 7:17
  • @Nick I am reading that the OP doesn't want any first level keys to be represented in the json (so that it ends up as a multidimensional array (with no keys) rather than an object)-- this is why array_values() serves well in the dupes. If it turns out that your interpretation is correct, do let me know. The question will need to be edited/clarified to be potentially reopened. (I don't know $x.) Commented Jan 6, 2020 at 7:52

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.