猿问

对 PHP 数组进行分组并获取最大值和最大值的总和

我有发布数据表单,需要按值进行数组分组,选择最大值和总和最大值我有一个想法,但我无法获得正确的值。数组如下,HTML 代码位于底部


Array

(

    [company] => Array

        (

            [0] => ABC

            [1] => BBC

            [2] => BBC

            [3] => ABC

        )


    [price] => Array

        (

            [0] => 10

            [1] => 5

            [2] => 20

            [3] => 15

        )


    [submit] => Submit

)

输出:-


1-ABC-10

4-ABC-15 …….Max price 15

2-BBC-5

3-BBC-20 ……. Max price 20

Total Price 35

Html 形式:-


<form action="?" method="post" name="form1" id="form1">

      Company: <input name="company[]" type="text" id="company[]" value="ABC"><br>

      Price: <input name="price[]" type="text" id="price[]" value="10">

      <br>

      Company: <input name="company[]" type="text" id="company[]" value="BBC"><br>

      Price: <input name="price[]" type="text" id="price[]" value="5">

      <br>

      Company: <input name="company[]" type="text" id="company[]" value="BBC"><br>

      Price: <input name="price[]" type="text" id="price[]" value="20">

      <br>

      Company: <input name="company[]" type="text" id="company[]" value="ABC"><br>

      Price: <input name="price[]" type="text" id="price[]" value="15">

      <br>

      <input type="submit" name="submit" id="submit" value="Submit">

</form>


郎朗坤
浏览 131回答 1
1回答

守候你守候我

$comapy = array("ABC","BBC","BBC","ABC");$price&nbsp; = array(10,5,20,15);//Group Your data Here ABC[10,15] ..$group = array();foreach($comapy as $key=>$val){&nbsp; &nbsp; &nbsp;$group[$val][] = $price[$key];}// this loop for check the max number and count total price$data&nbsp; &nbsp;= array();$total&nbsp; = 0;foreach($group as $key=>$val){&nbsp; &nbsp; $data[][$key] = $key."-".current($val);&nbsp; &nbsp; $data[][$key] = $key."-".max($val)." Max price : ".max($val);&nbsp; &nbsp; $total&nbsp; &nbsp; &nbsp; &nbsp; +=max($val);}// this foreach to convert your data to string$result = "";foreach($data as $key){&nbsp; &nbsp; $result .= "\n".current($key);}// and show your data like stringprint_r($result);print_r("\nTotal Price ".$total);/**&nbsp;result :&nbsp;&nbsp;ABC-10&nbsp;ABC-15 Max price : 15&nbsp;BBC-5&nbsp;BBC-20 Max price : 20&nbsp;Total Price 35&nbsp;//*************If you have more than 4 data in your array remplace foreach&nbsp;&nbsp;$groups with this code&nbsp;foreach($group as $key=>$val){&nbsp; &nbsp; for($i=0;$i<count($val);$i++){&nbsp; &nbsp; &nbsp; &nbsp;if($val[$i]!==max($val))&nbsp; &nbsp; &nbsp; &nbsp;$data[][$key] = $key."-".$val[$i];&nbsp; &nbsp; }&nbsp; &nbsp; $data[][$key] = $key."-".max($val)." Max price : ".max($val);&nbsp; &nbsp; $total&nbsp; &nbsp; &nbsp; &nbsp; +=max($val);&nbsp;}&nbsp;**/
随时随地看视频慕课网APP
我要回答