【问题标题】:Getting the Percentage of changes获取更改百分比
【发布时间】:2009-10-27 09:19:35
【问题描述】:

我怎样才能得到发生变化的百分比?

喜欢

 1. date    1343360810     objectId 1628
    field 10 value 3
 1. date    1242360811     objectId 1628
    field 10 value 5
 1. date    1243364812     objectId 1628
    field 10 value 5
 1. date    1240360814     objectId 1628
    field 10 value 5

这意味着值已在 4 个对象中更改了 1 次。 这将产生 25% 的百分比。

我的问题是如何在 PHP 中做到这一点。

我有这样的对象。

  [69]=>
  object(stdClass)#92 (6) {
    ["id"]=>
    string(7) "1824709"
    ["objectId"]=>
    string(4) "1628"
    ["type"]=>
    string(1) "0"
    ["field"]=>
    string(2) "10"
    ["value"]=>
    string(1) "3"
    ["date"]=>
    string(10) "1243360814"
  }

[70]=>
  object(stdClass)#93 (6) {
    ["id"]=>
    string(7) "1826225"
    ["objectId"]=>
    string(4) "1628"
    ["type"]=>
    string(1) "0"
    ["field"]=>
    string(2) "10"
    ["value"]=>
    string(1) "0"
    ["date"]=>
    string(10) "1243360814"
  }

【问题讨论】:

  • 你能把问题格式化一下吗?您需要使用 PHP 来执行此操作,还是从数据库中获取信息?
  • 我从数据库中获取它。是的,我需要在 PHP 中执行此操作
  • 只要最后一个值不等于当前值,就循环遍历您的数据计数。之后你得到它:更改/计数 * 100。
  • hmm.. 听起来不错,但从哪里获得更改?

标签: php arrays object


【解决方案1】:

迭代对象数组并跟踪值何时更改。应该这样做:

$oldvalue = false; // This is to exclude the first value from registering as a change
$changes = 0;
foreach($object_array as $obj) {
  if($oldvalue !== false && $obj->value != $oldvalue)
    $changes++;
  $oldvalue = $obj->value;
}
$change_percentage = $changes / count($object_array) * 100;

【讨论】:

  • 你从哪里得到 $change_percentage = $changes / count($objects) * 100; $对象?还是 $object_array 或 $obj ?
  • 你从哪里得到对象?
  • 在这个例子中,$object_array 最初被命名为 $objects,为了清晰起见,我重命名了它,但忘记更改最后一行。已修复,感谢提醒!
  • ...而 $object_array 指的是保存数据的数组。如果它不是数组形式(例如 MySQL 资源),则需要将 foreach() 替换为用于迭代数据的任何内容。
猜你喜欢
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-03
  • 2014-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多