从php

时间:2017-08-16 18:16:57

标签: php arrays

我有以下代码创建数组:

$query = $conn->query("select step1 FROM workflow1 ORDER BY id DESC limit 4;");

$array = Array();
while($result = $query->fetch_assoc()){
    $array[] = $result['step1'];
}

print_r($array);

当前输出:数组([0] => 1 [1] => 2 [2] => 52 [3] => 10)

如何查找数组值的百分比变化?即我想要的是

期望的输出:((1-2)/ 2) - > -50%,((2-52)/ 52) - > -96.15%等。我将把它放在html表中。

2 个答案:

答案 0 :(得分:1)

试试这个:

$datas = array( 0 => 1 ,1 => 2, 2 => 52 ,3 => 10 );

$output= array();

foreach ($datas as $key=>$value){
    $output[]= (($key-$value)/$value)*100;
}

print_r($output);

这是输出:

  

数组([0] => -100 [1] => -50 [2] => -96.153846153846 [3] => -70)

答案 1 :(得分:1)

试试这个:

$array = [1, 2, 52, 10];
$change = [];
foreach($array as $key=>$value){
  if(count($array) - 1 > $key) {
    $prev = $array[$key];
    $next = $array[++$key];    
    $percent_key = "((".$prev."-".$next.")/".$next.")";    
    $percent_value = (($prev-$next)/$next)*100;
  }
 $change[$percent_key] = $percent_value;
}
print_r($change);

输出:

  

数组([((1-2)/ 2)] => -50 [((2-52)/ 52)] => -96.153846153846 [((52-10)/ 10)] => ; 420)