如何将array_count_values的值存储在对象数组中?

时间:2012-02-10 09:54:06

标签: php arrays

我有下面的数组,按array_count_values函数排序,

Array
(
    [Session #1: Tues May 31st - Fri June 10th (1-5:30PM)#1 only: 1pmADV] => 3
    [Session #2: Tues June 14th - Fri June 24th (9-2:00PM)#1 only: 2pmADV] => 2
    [Session #4: Tues July 12th - Fri July 22nd (9-2:00PM)#1 only: 1:30pmADV] => 2

)

我需要将此数组转换为对象数组,如下所示

stdClass Object
(
    [Itemname] => Session #1: Tues May 31st - Fri June 10th (1-5:30PM)#1 only: 1pmADV
    [Quantity] => 3
)

stdClass Object
(
    [Itemname] => Session #2: Tues June 14th - Fri June 24th (9-2:00PM)#1 only: 2pmADV
    [Quantity] => 2
)
stdClass Object
(
    [Itemname] => Session #4: Tues July 12th - Fri July 22nd (9-2:00PM)#1 only: 1:30pmADV
    [Quantity] => 2
)

我该怎么做?

2 个答案:

答案 0 :(得分:4)

$arrayOfObjects = array();
foreach ($values as $Itemname => $Quantity) {
    $arrayOfObjects[] = (object)compact('Itemname', 'Quantity');
}

答案 1 :(得分:0)

这样的东西?:

foreach($array as $key => $value){
    $object = new stdClass;
    $object->Itemname = $key;
    $object->Quantity = $value;
    print_r($object);
}