I tried to find something about my problem but I haven't found anything yet.
I have a php array sorted as I want, but when I try to show it with javascript the order is altered, not all of it, but only the numbers. This example is reduced to simplify the problem, but I need this structure and even more arrays inside.
This is the code:
<?php
// array ordered as i need
$data = array(
"first" => array(
"test3" => array(),
"test1" => array(),
"test2" => array(),
"30" => array(),
"31" => array(),
"35" => array(),
),
"segond" => 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>
This is the result:
30
31
35
test3
test1
test2
Numbers are ordered but not the strings! I need to access the keys as values because they are names that I want to show. My guess is that when I get the keys they come ordered in the new array but I tried several things to maintain my order but javascript always sorts the array differently.
Can you help me? Thanks :)