doutuzhuohao6449 2013-02-11 20:03
浏览 29
已采纳

在嵌套的php数组中搜索$代码

Stack Overflowers,

Having attempted to dive into PHP, I appear to have got stuck; I have a pre-generated array where var_dump($codes) is as follows:

array(2) {
  [0]=>
  array(3) {
    ["code"]=>
    string(5) "01332"
    ["description"]=>
    string(19) "Derby Discount Code"
    ["discount_amount"]=>
    string(2) "15"
  }
  [1]=>
  array(3) {
    ["code"]=>
    string(5) "01283"
    ["description"]=>
    string(25) "South Derby Discount Code"
    ["discount_amount"]=>
    string(2) "20"
  }
}

I have form which _POSTs a variable of $code and would like to search in the array above to see if there is a match for $code in one of the nested arrays above. If so, I would like to be able to get the discount amount and description as individual variables.

So far I have the following:

if(in_array($code, $codes)) { 
    //apply discount code using $discount_amount
}

where $codes outputs the array posted at the top of this question.

  • 写回答

2条回答 默认 最新

  • drphfy1198 2013-02-11 20:07
    关注

    Quick little function you can use:

    function get_discount($arr, $code) {
        foreach($arr as $item) {
            if($item["code"] == $code) {
                return $item["discount_amount"];
            }
        }
    
        return NULL;
    }
    

    Where $arr is your array (that you dumped) and $code is the code you're checking for. Should return the discount, or NULL.

    Haven't had a chance to test it (typed it up here), but it should work as intended.

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

报告相同问题?

悬赏问题

  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输