PHP将简单数组转换为关联数组

时间:2018-03-29 08:17:48

标签: php arrays

我有一个看起来像这样的PHP数组......

$array1
Array
(
    [2] => 2
    [60] => 2
    [12] => 1
    [61] => 1
    [9] => 1
    [14] => 1
)

我正在尝试遍历它并创建一个看起来像这样的新数组......

$array2
Array
(
    [0] => stdClass Object
        (
            [id] => 2
            [count] => 2
        )
    [1] => stdClass Object
        (
            [id] => 60
            [count] => 2
        )
    [2] => stdClass Object
        (
            [id] => 12
            [count] => 1
        )
    [3] => stdClass Object
        (
            [id] => 61
            [count] => 1
        )
    [4] => stdClass Object
        (
            [id] => 9
            [count] => 1
        )
    [5] => stdClass Object
        (
            [id] => 14
            [count] => 1
        )

)

最好的方法是什么?有没有人有一个例子可以指出我在哪些方面取得了类似成果?

3 个答案:

答案 0 :(得分:2)

按照以下方式循环播放数组:

htOutputDetails = CType(lsListHashtables.Item(0, 1), Hashtable)

答案 1 :(得分:2)

试试这个:)

$array2 = [];
foreach($array1 as $key => $val){
    $array2[] = (object)["id" => $key, "count" => $val];
}

答案 2 :(得分:0)

您可以运行一个简单的循环来实现相同的目标。

$new_array = array();
foreach($array as $key => $val){
$new_array[] = (object) array("id"=> $id, "count"=>$val);
}