如果条件检查值存在于数组中

时间:2018-04-23 12:53:12

标签: php arrays

我有如下的数组

    data = [
     {
        "Payment_type":1,
        "amount":10000
     },

     {
        "Payment_type":1,
        "amount":40000
     },
     {
        "Payment_type":2,
        "amount":10000
     },
     {
        "Payment_type":2,
        "amount":20000
     }
]

现在我需要检查Payment_type = 1是否获得所有金额的Payment_type 1,否则获得其他付款类型的所有金额

我需要输出

   Payment type 1
       ---10000
       ---40000
   Payment type 2
       ---10000
       ---20000

我尝试使用以下代码

   foreach($data as $d)
   {
       if($d->Payment_type == 1)
       {
           echo $d->amount;
       }
       else
       {
           echo $d->amount;
       }
   }

我如何获得这些价值?

4 个答案:

答案 0 :(得分:1)

在找出数据是类型1还是2后,不是直接回显数量,而是填满2个数组(类型1和类型2)。然后,稍后,迭代这些数组。这样,数据将按类型排序。我的示例将与您的问题完全相同。

$dataOfType1 = array();
$dataOfType2 = array();

foreach($data as $d)
{
   if($d->Payment_type == 1)
   {
       $dataOfType1[] = $d;
   }
   else
   {
       $dataOfType2[] = $d;
   }
}

// iterate over first array (type 1)
echo "Payment type 1 <br>";
foreach($dataOfType1 as $d){
  echo "---".$d->amount . "<br>";
}

// iterate over second array (type 2)

echo "Payment type 2 <br>";
foreach($dataOfType2 as $d){
  echo "---".$d->amount . "<br>";
}

修改:在循环之外移动付款类型标头

答案 1 :(得分:0)

使用我自编写的类GrumpyHelper编写的函数,有一个名为groupArray的函数。

function groupArray($arr, $group, $preserveSubArrays = false, $preserveGroupKey = false) {
    $temp = array();
    foreach($arr as $key => $subarray) {
        $groupBy = $subarray[$group];
        if(!$preserveGroupKey) {
            unset($arr[$key][$group]);
        }
        if(!array_key_exists($groupBy, $temp)) {
            $temp[$groupBy] = array();
        }
        if(!$preserveSubArrays && count($arr[$key])==1) {
            $temp[$groupBy][] = current($arr[$key]);
        } else {
            $temp[$groupBy][] = $arr[$key];
        }
    }
    return $temp;
}

您可以将数据插入此功能,如下所示:

print_r(groupArray($data, "Payment_type", false, false));

这会得到结果:

Array
(
    [1] => Array
        (
            [0] => 10000
            [1] => 40000
        )

    [2] => Array
        (
            [0] => 10000
            [1] => 20000
        )

)

密钥等于原来的Payment_type

现在你只需要循环来获得总数。

$totals = [];
foreach($data_from_groupArray as $key => $amounts) {
    foreach($amounts as $amount) {
        if(empty($totals[$key])) $totals[$key] = 0;
        $totals[$key] += $amount;
    }
}

这会给你结果:

Array
(
    [1] => 50000
    [2] => 30000
)

如果密钥等于前Payment_type,则该值等于一起添加的所有金额。

或者,对于您在上面指定的输出,请执行此操作而不是上面的循环:

foreach($data_from_groupArray as $key => $amounts) {
    echo "Payment type {$key} <br>";
    foreach($amounts as $amount) {
        echo "   ---{$amount}<br>";
    }
}

注意:无论您有多少Payment_type@model InventoryModule.Models.Masters.Ledger @{ ViewData["Title"] = "Create"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Create</h2> <h4>Ledger</h4> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="Create" asp-antiforgery="true" id="fromLedger"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="LedgerGroupId" class="control-label"></label> <select asp-for="LedgerGroupId" class="form-control" asp-items="ViewBag.LedgerGroupId"> <option value="0">--Select Group--</option> </select> <div class="modal fade" role="dialog" id="ModalCreate"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">x</button> <h4 class="modal-title">Create Product Group</h4> </div> <div class="modal-body" id="modelPartial"> </div> </div> </div> </div> <button type="button" class="btn btn-info btn-sm" id="btnModel"> New Group </button> </div> <div class="form-group"> <label asp-for="LedgerName" class="control-label"></label> <input asp-for="LedgerName" class="form-control" /> <span asp-validation-for="LedgerName" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Address" class="control-label"></label> <input asp-for="Address" class="form-control" /> <span asp-validation-for="Address" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Email" class="control-label"></label> <input asp-for="Email" class="form-control" /> <span asp-validation-for="Email" class="text-danger"></span> </div> <div class="form-group"> <div class="checkbox"> <label> <input asp-for="IsActive" /> @Html.DisplayNameFor(model => model.IsActive) </label> </div> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-default" /> </div> </form> </div> </div> <div> <a asp-action="Index">Back to List</a> </div> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js" asp-fallback-src="~/lib/jquery/dist/jquery.min.js" asp-fallback-test="window.jQuery" crossorigin="anonymous" integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk"> </script> <script type="text/javascript"> $(document).ready(function () { $("#btnModel").click(function(e) { $.ajax({ type: 'Get', url: '@(Url.Action("ShowPartial","Ledger"))', success: function (respose) { $('#modelPartial').html(respose); $('#ModalCreate').modal('show'); }, cache: false }); }); }) </script> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} } ,此代码都会有效。

答案 2 :(得分:0)

假设您的数据符合所显示的顺序(即数组按payment_type排序),这将适用于:

<?php
    $data = array(array("Payment_type"=>1,"amount"=>10000),
                  array("Payment_type"=>1,"amount"=>40000),
                  array("Payment_type"=>2,"amount"=>10000),
                  array("Payment_type"=>2,"amount"=>20000)
                 );

    #var_dump($data);
    $currenttype = 0;
    foreach($data as $d)
    {
        if ($currenttype != $d['Payment_type'])
        {
            echo "&nbsp;&nbsp;&nbsp;&nbsp;Payment type $d[Payment_type]<br>";
            $currenttype=$d['Payment_type'];
        }

        echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;---$d[amount]<br>";
   }
?>

&nbsp;将为您提供您想要的输出,但在现实生活中使用CSS更好。

输出:

    Payment type 1
        ---10000
        ---40000
    Payment type 2
        ---10000
        ---20000

答案 3 :(得分:0)

create function,它将$id作为参数并返回过滤后的数据:

function get_by_type($id, $array){
    $arr = array();
    foreach($array as $a){
        if($a['Payment_type'] == $id){
                array_push($arr, $a);
        }
    }
    return $arr;
}