PHP multidimensional array search by value

前端 未结 23 3251
情歌与酒
情歌与酒 2020-11-21 04:45

I have an array where I want to search the uid and get the key of the array.

Examples

Assume we have the following 2-dimensional array:

<
23条回答
  •  礼貌的吻别
    2020-11-21 05:35

    If question i.e.

    $a = [
         [
           "_id" => "5a96933414d48831a41901f2",
           "discount_amount" => 3.29,
           "discount_id" => "5a92656a14d488570c2c44a2",
         ],
         [
           "_id" => "5a9790fd14d48879cf16a9e8",
           "discount_amount" => 4.53,
           "discount_id" => "5a9265b914d488548513b122",
         ],
         [
           "_id" => "5a98083614d488191304b6c3",
           "discount_amount" => 15.24,
           "discount_id" => "5a92806a14d48858ff5c2ec3",
         ],
         [
           "_id" => "5a982a4914d48824721eafe3",
           "discount_amount" => 45.74,
           "discount_id" => "5a928ce414d488609e73b443",
         ],
        [
           "_id" => "5a982a4914d48824721eafe55",
           "discount_amount" => 10.26,
           "discount_id" => "5a928ce414d488609e73b443",
         ],
       ];
    

    Ans:

    function searchForId($id, $array) {
        $did=0;
        $dia=0;
       foreach ($array as $key => $val) {
           if ($val['discount_id'] === $id) {
               $dia +=$val['discount_amount'];
               $did++;
           }
       }
        if($dia != '') {
            echo $dia;
            var_dump($did);
        }
       return null;
    };
    print_r(searchForId('5a928ce414d488609e73b443',$a));
    

提交回复
热议问题