为了轻松导入数据库数据,我尝试编写一些PHP代码以帮助我。我有2个数组," list"这是常规的aray。其他" order1"是一个关联数组。我试图比较第一个值和第二个键来制作我需要的列表..像多重查找和替换...
array:list
[0] => Apple
[1] => Apple
[2] => Apple
[3] => Apple
[4] => Bannana
[5] => Mango
[6] => Mango
[7] => Mango
[8] => Mango
[9] => Mango
[10] => Pear
[11] => Pear
[12] => Pear
[13] => Pear
[14] => Pineaple
[15] => Strawberry
[16] => Strawberry
[17] => Watermelon
[18] => Watermelon
[19] => Watermelon
[20] => Watermelon
数组:order1
[Apple] => 1
[Bannana] => 2
[Mango] => 3
[Pear] => 4
[Pineaple] => 5
[Strawberry] => 6
[Watermelon] => 7
我想得到:
1
1
1
1
2
3
3
3
3
3
4
4
4
4
5
6
6
7
7
7
7
但是...
$final=array();
foreach($list as $keyl => $valuel){
foreach($order1 as $keyo => $valueo){
if($valuel==$keyo) {
$final[].=$valueo;
}
}
}
print_r($final);
让我只有7,最后一个元素..
var的递归/生命有什么问题吗?但我似乎无法得到它..
答案 0 :(得分:3)
因为您感兴趣的部分是"值" $order1
具有您已知道的索引,您不会需要内循环,而只需使用isset()
来验证索引是否存在,如果存在,则参考直接。
例如:
$final = array();
foreach ($list as $index => $key_name) {
if (isset($order1[$key_name])) {
$final[] = $order1[$key_name];
}
}
print_r($final);
答案 1 :(得分:2)
我认为您在数组初始化时搞砸了,因为下面的代码按预期工作(根据我的理解)
$list = ["Apple", "Apple", "Apple", "Apple", "Bannana", "Mango", "Mango", "Mango", "Mango", "Mango", "Pear", "Pear", "Pear", "Pear", "Pineaple", "Strawberry", "Strawberry", "Watermelon", "Watermelon", "Watermelon", "Watermelon"];
$order1 = [
"Apple" => 1,
"Bannana" => 2,
"Mango" => 3,
"Pear" => 4,
"Pineaple" => 5,
"Strawberry" => 6,
"Watermelon" => 7
];
$final=array();
foreach($list as $keyl => $valuel){
foreach($order1 as $keyo => $valueo){
if($valuel==$keyo) {
$final[].=$valueo;
}
}
}
print_r($final)