ua1
ua1

Reputation: 107

PHP sorted Array is not sorted in JS after json_encode

I have two arrays in PHP. I sort the first array like this:

arsort($array1);

And then output the arrays like that:

foreach ($array1 as $key => $val) {
    $output .= "<tr>
    <td>".$array1[$key]."</td>
    <td>".$array2[$key]."</td>
    </tr>";
}
print($output);

Here is what the Arrays look like:

$array1 = [21, 12, 64, 87, 5, 823, ...]
$array2 = ["label1", "label2", "label3", "label4", ...]

Every element in $array2 is associated with an element in $array1 so in this example the element "label1" should be linked to the element 21 (both key 0) but if I sort $array1 and the element keys change they should also change in $array2

I also need to use $array2 in Javascript with the same order so I use json_encode like that:

$arr2 = json_encode($array2);

$somejs = <<<ECHO
<script type="text/javascript">

var arr2 = $arr2;
for (i = 0; i < arr2.length; i++) {
    console.log(arr2[i]);
}
</script>
ECHO;
echo $somejs;

But it doesn't get displayed like in the foreach loop but in its original order (keys: 0, 1, 2, 3, ...)

Is it somehow possible to pass the keys to the created Javascript Array or do you guys have another, maybe better solution?

Hope my question is clear tell me if there is a problem :)

Thanks

Upvotes: 2

Views: 261

Answers (1)

Barmar
Barmar

Reputation: 781761

Make an array $array3 that contains the reordered version of $array2. You can do this while you're print the table.

$array3 = array();
foreach ($array1 as $key => $val) {
    $output .= "<tr>
    <td>".$array1[$key]."</td>
    <td>".$array2[$key]."</td>
    </tr>";
    $array3[] = $array2[$key];
}
print($output);

Then use json_encode($array3) when you create the Javascript.

Upvotes: 2

Related Questions