Php [array comparison output] $ array1array (,); this data value is fixed. $ Array2array (,); the data value is not fixed. Effect: After comparison between array2 and array1, the value that array2 does not have is replaced by 0. Result:,. how can I implement this? ------ solution ------------ php [array comparison output]
$ Array1 = array ("1", "2", "3", "4", "5", "6"); // This data value is fixed.
$ Array2 = array ("1", "3", "6", "4"); // the data value is not fixed.
Effect:
After comparison between array2 and array1, the value that array2 does not have is replaced by 0.
Result:
1, 0, 3, 4, 0, 6
How can this problem be achieved?
------ Solution ----------------------
$arr = array();
$x;
foreach($array2 as $k => $v) {
x = array_search($v,$array1);
if (x) {
$arr[$k] = $v;
} else {
$arr[$k] = 0;
}
}
------ Solution ----------------------
$ Array1 = array ("1", "2", "3", "4", "5", "6"); // This data value is fixed.
$ Array2 = array ("1", "3", "6", "4"); // the data value is not fixed.
$ Arr = array ();
Foreach ($ array1 as $ v ){
$ Arr [] = in_array ($ v, $ array2 )? $ V: 0;
}
Print_r ($ arr );
------ Solution ----------------------
Reference
#1
$ Arr = array ();
$ X;
Foreach ($ array2 as $ k => $ v ){
X = array_search ($ v, $ array1 );
If (x ){
$ Arr [$ k] = $ v;
} Else {
$ Arr [$ k] = 0;
}
}
Array_search () returns the matched key name. when the first key is matched, the key name is 0, and the if statement does not exist. a problem exists here.
------ Solution ----------------------
Php contains an array comparison function array_diff.
------ Solution ----------------------
Yes, you can use array_diff
$a = array("1","2","3","4","5","6");
$b = array("1","3","6","4");
$c = $a;
foreach(array_diff($a, $b) as $k=>$v) $c[$k] = 0;
print_r($c);
Array
(
[0] => 1
[1] => 0
[2] => 3
[3] => 4
[4] => 0
[5] => 6
)
------ Solution ----------------------
$ Array1 = array ("1", "2", "3", "4", "5", "6"); // This data value is fixed.
$ Array2 = array ("1", "3", "6", "4"); // the data value is not fixed.
$ C = array_diff ($ array1, $ array2 );
Foreach ($ c as $ k => $ v ){
$ Array1 [$ k] = 0;
}
Print_r ($ array1 );
Array
(
[0] => 1
[1] => 0
[2] => 3
[3] => 4
[4] => 0
[5] => 6
)