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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘