Js php array comparison, jsphp Array
In addition to definitions and operations, php and javascript arrays have many differences. Now let's discuss it.
1. We all know that php compares two arrays to see if they are all equal (value, index ).
$ A = array (, 3); $ B = array (, 3); echo ($ a = $ B); // If output is 1, what about javascript: see the code returned by the following code: <script type = "text/javascript"> var a = ['A', 'B', 'C']; var B = ['A', 'B', 'C']; console. log (a = B); // the output value is false </script>
Why? Because javascript objects often become reference types, comparison of objects is reference comparison, and they are equal only when they reference the same base object. The following code compares arrays of reference types.
Var a = ['A', 'B', 'C']; var B = a; console. log (a = B); // The value of outupt is true.
2. php and javascript assign values to an array object to a variable is also different. Javascrpt only assigns a reference value. The object is not copied once in this province, while php assigns a copy. It may not be clear enough. Please refer to the Code:
<? Php $ a = array (1, 2, 3); $ B = $ a; $ B [] = 6; print_r ($ a); echo '<br/> '; print_r ($ B); // Array ([0] => 1 [1] => 2 [2] => 3) // Array ([0] => 1 [1] => 2 [2] => 3 [3] => 6) js Code: var a = ['A ', 'B', 'C']; var B = a; B [3] = 'D'; console. log (a); console. log (B); // output // ["a", "B", "c", "d"] index12.html: 12 // ["", "B", "c", "d"] index12.html: 13
How does js receive PHP arrays?
1. if you understand the JSON data format, this problem is very simple:
<? Php
$ A = array ('1', '2', '3 ');
?>
<Script language = "javascript">
Var obj = eval ('<? Php echo json_encode ($ a);?> ');
Alert (obj [0]);
Alert (obj [1]);
Alert (obj [2]);
</Script>
2. If you do not understand JSON, use the traditional method:
<Script language = "javascript">
Var arr = new Array ();
<? Php
Foreach ($ a as $ key => $ value ){
Echo "arr [$ key] = '$ value'; \ n ";
}
?>
Alert (arr [0]);
</Script>
How to submit a JS array to PHP
JS uses join to convert the array to a string and pass it to PHP. PHP then uses explode to convert the obtained string to an array. For example:
Called JS:
<Script type = "text/javascript">
Var oCC = new TClientCheck ();
Var str = oCC. join ('| ');
Location. href = 'but. php? Str = '+ str;
</Script>
PHP:
<? Php
$ Str = $ _ GET ["str"];
$ OCC = explode ('|', $ str );
Print_r ($ oCC );
?>