我有一个对象数组如何删除重复值并计算它们

时间:2018-01-29 14:23:10

标签: php arrays

array(3) { 
   [0]=> object(stdClass)#43 (5) { 
      ["id"]=> string(3) "148" 
      ["questionResId"]=> string(2) "76" 
      ["optionText"]=> string(17) "some Cute Moment." 
      ["optionId"]=> string(2) "30" 
      ["optionAnswer"]=> string(4) "test" } 
   [1]=> object(stdClass)#38 (5) { 
      ["id"]=> string(3) "142" 
      ["questionResId"]=> string(2) "72" 
      ["optionText"]=> string(17) "some Cute Moment." 
      ["optionId"]=> string(2) "30" 
      ["optionAnswer"]=> string(4) "test" } 
   [2]=> object(stdClass)#41 (5) { 
      ["id"]=> string(3) "221" 
      ["questionResId"]=> string(3) "136" 
      ["optionText"]=> string(17) "some Cute Moment." 
      ["optionId"]=> string(2) "30" 
      ["optionAnswer"]=> string(4) "Good" } 
}

我有如上所述的数组对象如何从PHP中的数组中删除重复值并计算每个元素的出现次数

out like like

test 2 
good 1

1 个答案:

答案 0 :(得分:1)

array_count_values获得您想要的结果

array_count_values(array_map(function($x) { return $x->optionAnswer;}, $arr));

结果

Array( [test] => 2, [Good] => 1 )