我需要计算数组值

时间:2018-08-30 03:46:04

标签: php arrays

我需要计算数组值

$str = '"Cat","A","A","A","A"';

$abc=array($str, "A","Cat","Dog","A","Dog");
print_r(array_count_values($abc));

结果出来了

 Array ( ["Cat","A","A","A","A"] => 1 [A] => 2 [Cat] => 1 [Dog] => 2 )

但是我需要这样:

 Array ( [A] => 6 [Cat] => 2 [Dog] => 2 )

6 个答案:

答案 0 :(得分:4)

这是因为$str是字符串而不是数组。因此,它作为一个元素添加到$abc数组中。

您可以使用explode函数将其转换为数组:

$str = '"Cat","A","A","A","A"';
$arr = explode(',', $str);
// So $arr is Array([0] => "Cat", [1] => "A", [2] => "A", [3] => "A", [4] => "A")

然后,您需要删除每个元素周围的双引号。 我建议使用trim函数和array_map函数将其应用于每个元素:

$arr = array_map(function ($item) { return trim($item, '"'); }, $arr);
// $arr is Array([0] => Cat, [1] => A, [2] => A, [3] => A, [4] => A)

然后您可以将其与其余值合并:

$abc = array_merge($arr, array("A","Cat","Dog","A","Dog"));
print_r(array_count_values($abc));
// Should be Array ( [A] => 6 [Cat] => 2 [Dog] => 2 )

答案 1 :(得分:1)

那么,不要将字符串放入数组中并期望将其视为数组值。要么将字符串修改为数组,然后合并两个数组,要么解析字符串并将每个值添加到数组中。

对于后一种方法,您可以执行以下操作:

$str = '"Cat","A","A","A","A"';
$abc = array("A","Cat","Dog","A","Dog");
$splitstr = explode(',',str_replace('"','',$str));

$finalarray = array_merge($abc,$splitstr);

print_r(array_count_values($finalarray));

答案 2 :(得分:1)

根据PHP manual,您可以使用array_merge ( array $array1 [, array $... ] )

示例:

$str = '"Cat","A","A","A","A"';
$abc=array_merge($str, array("A","Cat","Dog","A","Dog"));
print_r(array_count_values($abc));

答案 3 :(得分:0)

您将第一个元素完全放在字符串中。分开

  $str = '"Cat","A","A","A","A"';
  $abc=array(  "Cat","A","A","A","A", "A","Cat","Dog","A","Dog"); 
  print_r(array_count_values($abc));

或合并数组

  $arr1 = ["Cat","A","A","A","A"];
  $abc=array_merge(  $arr1,["A","Cat","Dog","A","Dog"]); 
  print_r(array_count_values($abc));

Demo

答案 4 :(得分:0)

您的逻辑有缺陷,您应该首先正确创建数组

$str = '"Cat","A","A","A","A"';
$abc = array("A","Cat","Dog","A","Dog"); 
$splitstr = explode(',',str_replace('"','',$str)); 
$finalarray = array_merge($abc,$splitstr);  

print_r(array_count_values($finalarray));

现在您将获得理想的结果。

答案 5 :(得分:0)

您正在使用array_count_values来计算$abc数组的所有值。但是,$str是一个字符串,而不是一个数组,而是$abc数组的一个元素。

最简单的解决方案是通过删除$str双引号(使用"方法)并将str_replace作为分隔符(使用{ {1}}方法)。只需添加以下代码段中的一行即可完成此操作:

,

您可以看到this script in this link的执行情况。