Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用数组的php计数问题_Php_Arrays - Fatal编程技术网

使用数组的php计数问题

使用数组的php计数问题,php,arrays,Php,Arrays,我有一些非常不同的东西,我写的数组映射代码有问题。我请求帮助,有人很友善地建议他写下面的代码。然而,它似乎有几个错误,因为我没有写它,也不太熟悉array_walk,所以我需要一些帮助才能让它工作 问题是,它不是提供数据库中每个对象的实际计数,而是计算类型。例如,如果类型_2的数量为3,则显示为1,因为只有一列类型为_2 $bl_type = $wpdb->get_results("SELECT Type FROM mytablenamehere"); $bl_typ

我有一些非常不同的东西,我写的数组映射代码有问题。我请求帮助,有人很友善地建议他写下面的代码。然而,它似乎有几个错误,因为我没有写它,也不太熟悉array_walk,所以我需要一些帮助才能让它工作

问题是,它不是提供数据库中每个对象的实际计数,而是计算类型。例如,如果类型_2的数量为3,则显示为1,因为只有一列类型为_2

$bl_type = $wpdb->get_results("SELECT Type FROM mytablenamehere");

$bl_type = [
  (object)['Type' => 'Type_0'],
  (object)['Type' => 'Type_1'],
  (object)['Type' => 'Type_1'],
  (object)['Type' => 'Type_1'],
  (object)['Type' => 'Type_2'],
];

$types = [
  (object)['Type' => 'Type_1'],
  (object)['Type' => 'Type_2'],
  (object)['Type' => 'Type_3'],
  (object)['Type' => 'Type_4'],
];

$counts = array_count_values(array_column($bl_type, 'Type'));
array_walk($types, function($item) use ($counts) {
    $item->Frequency = $counts[$item->Type] ?? 0;
});

echo '<table id="count"><tr>';
foreach($types as $item) {
    echo '<th>', $item->Type, '</th>';
}
echo '</tr><tr>';
foreach($types as $item) {
    echo '<td>', $item->Frequency, '</td>';
}
echo '</tr></table>';
阵列的一个示例输出:

阵列4{ [0]=>objectstdClass2657 1{[Type]=>string8类型_0} [1] =>objectstdClass2658 1{[Type]=>string7 Type_1} [2] =>objectstdClass2659 1{[Type]=>string7 Type_1} [3] =>objectstdClass2660 1{[Type]=>string7 Type_1} [4] =>objectstdClass2661 1{[Type]=>string8 Type_2}


显示代码后,您根本不使用数据库中的数据:

$bl_type=$wpdb->get_results从MyTableName中选择类型此处; $bl_type=[//这里的赋值就是问题所在 对象['Type'=>'Type_0'], 对象['Type'=>'Type_1'], 对象['Type'=>'Type_1'], 对象['Type'=>'Type_1'], 对象['Type'=>'Type_2'], ]; 第二个赋值$bl_type=[…]覆盖了变量$bl_type的内容,该变量以前保存了数据库查询结果。因此,无论数据库存储了什么,您都只能得到相同的结果

因此,只需删除第二个赋值,只保留这一行:

$bl_type=$wpdb->get_results从MyTableName中选择类型此处;
错误是意外的?你能给出完整的错误吗?同样对于示例数据,你希望输出是什么样子的。澄清。它告诉我?问号是unexpcted,这表明你使用的是一个古老的PHP版本,没有空合并运算符。使用PHPV7。错误来自DW,因为我看不到错误它在站点上是正确的,因此在野外可能不是问题,但是计数问题在站点上肯定不起作用。您对此代码有什么问题?出现了几个错误,您可以分享它们吗?