我已将CSV转换为二维数组,其中以下数组结构存储列和行数据
$table['status'] = ['active', 'active', 'inactive'];
$table['plan'] = ['annual', 'weekly', 'weekly '];
$table['spend'] = ['12,000', '19,000', '0' ];
print_r($table);
将如下所示:
( [status] => Array ( [0] => active [1] => active [2] => inactive )
[plan] => Array ( [0] => annual [1] => weekly [2] => weekly )
[spend] => Array ( [0] => 12,000 [1] => 19,000 [2] => 0 ) )
我想使用本机 PHP 数组函数来查询数组,而不必编写具有嵌套条件的循环。如果这是一个MySQL数据库,并且我想找到具有活动状态和每周计划的帐户的支出总和,我将简单地运行以下查询
SELECT SUM('Spend') FROM table WHERE status = 'Active' AND plan = 'Weekly';
但相反,我必须采用以下方法 for 循环
for ($index = 1; $index < count($table); $index++){
if (($table['status'][$index] == 'active') && ($table['plan'][$index] == 'weekly')){
$spend[$index] = $table['spend'][$index];
}
}
echo array_sum($spend);
这种方法让我头疼。是否有一个明显的解决方案将其重构为 php 的本机数组函数,或者乱七八糟的显式循环是不可避免的?
没有任何本机函数可以执行您想要的操作。将 CSV 文件中的信息存储到数据库中有什么问题?
如果这根本不是一种选择,请尝试foreach
循环,它们更干净。
$spend = array();
foreach ($table['spend'] as $key => $amount)
{
if ($table['status'][$key] == 'active' && $table['plan'][$key] == 'weekly')
{
$spend[] = $amount;
}
}
虽然它不能解决循环问题,但它确实有助于清理它们,因此您不会太失去理智。
使用数组键获取所有"活动"键,然后仅遍历这些键以查找匹配项。
$keys = array_keys($table['status'], 'active');
foreach($keys as $key)
{
if($table['plan'][$key] == 'weekly')
{
$spend[] = $table['spend'][$key];
}
}
print_r($spend);
花费: 数组 ( [0] => 19,000 )
这
很混乱,但我找到了一种方法
$keys = array_intersect(array_keys($table['status'], 'active'), array_keys($table['plan'], 'weekly'));
$subs['total'] = array_intersect_key($table['spend'], array_flip($keys));
print_r(array_sum($subs['total']));