查找特定多维数组php的总和

时间:2017-04-10 06:36:12

标签: php foreach sum

(a.a = q.a)

我将在下周完成此代码。此外,我是一名学生,刚开始使用PHP。我的问题是我试图在给定数组中输出<?php $bookrec=array( 'book1'=>array('callno'=>123005,'price'=>number_format(1380,2),'desc'=>'Attack on Titan Anthology'), 'book2'=>array('callno'=>123006,'price'=>number_format(844,2),'desc'=>'Binge'), 'book3'=>array('callno'=>123004,'price'=>number_format(598,2),'desc'=>'A Work in Progress'), 'book4'=>array('callno'=>123003,'price'=>number_format(668,2),'desc'=>'The Amazing Book is Not on Fire: The World of Dan and Phil'), 'book5'=>array('callno'=>123002,'price'=>number_format(760,2),'desc'=>'Children of Eden: A Novel') ); $sumbook=array(); echo "<table>"; echo "<tr><b> <td>Call Number</td><td>Price</td><td>Book Title</td> </b></tr>"; while(list($booknum,$rec)=each($bookrec)){ echo "<tr>"; foreach($rec as $data){ echo "<td>". $data."<br></td>"; foreach($data as $k => $val){ if(array_key_exists($val,$sumbook)) $sumbook[$val]['price']=$sumbook[$val]['price']+$data['price']; else if($k == 'desc' && $k == 'callno') $sumbook[$val] = $data; } } } echo "<br></tr>"; echo "</table>"; echo "TOTAL AMOUNT: Php ".$sumbook;?> 的总和,但它给了我这个错误:

  

为foreach提供的参数无效

我也尝试过各种方法解决这个问题,但我并没有真正理解。请帮忙。 :)谢谢!!

3 个答案:

答案 0 :(得分:1)

<?php
$bookrec=array(
'book1'=>array('callno'=>123005,'price'=>number_format(1380,2),'desc'=>'Attack on Titan Anthology'),
'book2'=>array('callno'=>123006,'price'=>number_format(844,2),'desc'=>'Binge'),
'book3'=>array('callno'=>123004,'price'=>number_format(598,2),'desc'=>'A Work in Progress'),
'book4'=>array('callno'=>123003,'price'=>number_format(668,2),'desc'=>'The Amazing Book is Not on Fire: The World of Dan and Phil'),
'book5'=>array('callno'=>123002,'price'=>number_format(760,2),'desc'=>'Children of Eden: A Novel')
);

$sumbook=array();

echo "<table>";
echo "<tr><b>
    <td>Call Number</td><td>Price</td><td>Book Title</td>
    </b></tr>";
 foreach($bookrec as $key1=>$rec )
{  
    echo "<tr>";

    foreach($rec as $key2=>$data)
    {

       echo "<td>". $data."<br></td>";

          if($key2="price")
          {

            $total+=$data;
          }

     }

    echo "</tr><br>";
}
echo "<br></tr>";
echo "</table>";
echo "TOTAL AMOUNT: Php ".$sumbook;?>

答案 1 :(得分:0)

你的第一个foreach循环有一个错误的变量名,你的数组初始化为。

foreach( $ bookrec as $ data){

}

答案 2 :(得分:0)

我认为你有很多循环错误,只需遵循此代码,并了解如何使用foreach

迭代数组
    $sumbook=array();

    $total =0;
    echo "<table>";
    echo "<tr><b>
          <td>Call Number</td><td>Price</td><td>Book Title</td>
          </b></tr>";

    foreach($bookrec as $key1=>$rec )
    {  
        echo "<tr>";

        foreach($rec as $key2=>$data)
        {

           echo "<td>". $data."<br></td>";

              if($key2="price")
              {

                $total+=$data;
              }

         }

        echo "</tr><br>";
    }

    echo "</table>";
    echo "TOTAL AMOUNT: Php ".$total;

    ?>