如何在php中计数和显示数组值

时间:2018-11-27 10:33:12

标签: php

我下面有一个对象数组数据。

$rooms= Single room,Single room,Single room ;

我要在此处以以下格式显示数据

3 X Single room 

例如以下格式的房间

Single room, Double room , Single room

那我需要放的是

2x single room 
1x Double room

如何获得这种结果,请告诉我,我尝试了array_count_valuesarray_unique,但没有得到结果。请任何人告诉我

$str = rtrim(implode(",",explode("#", Single Room#DOuble Room#Single Room))); 
$ss= str_replace(' ','',$str); 
$ss1= str_replace(',',' ',$ss); 
$rooms = explode(' ', $ss1); 
//Count each occurence of values 
$countedValues = array_count_values($rooms); 
//Build strings from value and display them. 
foreach( $countedValues as $roomType=>$count ){ 
    echo $count . 'x ' . $roomType . '<br />'; 
}

1 个答案:

答案 0 :(得分:0)

我不知道您如何使用array_count_values,因为您尚未发布代码,请以后再发布代码。下面是一个工作示例,可以提供所需的输出。

<?php

$rooms = "Single room,Single room,Single room,Double room";
$rooms = explode(',', $rooms); // array of rooms
//Count each occurence of values
$countedValues = array_count_values($rooms);

//Build strings from value and display them.
foreach( $countedValues as $roomType=>$count ){
    echo $count . 'x ' . $roomType . '<br />';
}

?>

这给了我输出:

3x Single room
1x Double room

请注意,您的问题包括以下内容:

$rooms= Single room,Single room,Single room ;

这不是有效的数组格式。您应该改用以下方法:

$rooms = array("Single room","Single room","Single room");