dongzong8110 2014-05-25 21:42
浏览 167
已采纳

PHP比较一个值和另一个数组的键

In order to import database data with ease, I have tried to write some php code in order to help me out. I have 2 arrays, "list" wich is regular aray. Other "order1" is an associative array. I'm trying to compare value of first with keys of second to make list that I need.. Something like multi find and replace..

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 

array: order1

[Apple] => 1
[Bannana] => 2
[Mango] => 3
[Pear] => 4
[Pineaple] => 5
[Strawberry] => 6
[Watermelon] => 7

I want to get:

1
1
1
1
2
3
3
3
3
3
4
4
4
4
5
6
6
7
7
7
7

But..

$final=array();
foreach($list as $keyl => $valuel){
   foreach($order1 as $keyo => $valueo){
      if($valuel==$keyo) {
        $final[].=$valueo;
      }
   }
}
print_r($final);

gets me just 7, last element..

Something wrong with recursion/life of var? But I can't seem to get it..

  • 写回答

2条回答 默认 最新

  • doushang1880 2014-05-25 21:45
    关注

    Since the part you're interested in is the "value" of $order1 which has indexes you'll know, you won't need the inner-loop and instead you can just use isset() to verify that the index exists and, if so, reference it directly.

    For instance:

    $final = array();
    foreach ($list as $index => $key_name) {
        if (isset($order1[$key_name])) {
            $final[] = $order1[$key_name];
        }
    }
    
    print_r($final);
    

    Codepad Example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题