I have spent time searching for a solution to my issue, but so far, I have not been successful in finding one.
My PHP array is arranged exactly as I need it to be, but when I attempt to display it using JavaScript, the order gets distorted, specifically when it comes to numbers. Although I have simplified the example here, I require this structure and even more arrays nested inside.
Here is the code snippet:
<?php
// array ordered as i need
$data = array(
"first" => array(
"test3" => array(),
"test1" => array(),
"test2" => array(),
"30" => array(),
"31" => array(),
"35" => array(),
),
"second" => array(
"test1" => array(),
"test2" => array(),
),
);
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var data = <?php echo json_encode($data); ?>;
$(document).on('click', 'input[type=button][name=test]', function() {
var fields = Object.keys(data['first']);
for(i=0; i<fields.length; i++) {
$('body').append('<p>'+fields[i]+'</p>');
}
});
</script>
</head>
<body>
<input type="button" name="test" value="Test me">
</body>
</html>
Upon execution, the output is as follows:
30
31
35
test3
test1
test2
The numbers are arranged correctly, but the strings are not! I need to treat the keys as values because they represent names that I want to display. I suspect that when fetching the keys, they are arranged in a new array, and despite my efforts to maintain the order, JavaScript always reorders the array differently.
Could you provide assistance? Thank you :)