将数组分配给php中的单个键

时间:2014-02-17 23:40:21

标签: php arrays

我正在尝试将数组分配给单个键。

我正在尝试将值数组分配给单个键,如下所示:

$ entity_items_array [$ entity_restrict] = $ entity_items;

密钥$ entity_restrict看起来像这样:

'User'

数组$ entity_items如下所示:

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12 [13] => 13 [14] => 14 [15] => 15 [16] => 16 [17] => 17 [18] => 18 [19] => 19 [20] => 20 [21] => 21)

我正在尝试按如下方式分配密钥:

但出于某种原因,当我查看$ entity_items_array时,我得到的值是:

Array ( [0] => user )

我做错了什么?我没有正确地将数据分配给数组吗?

2 个答案:

答案 0 :(得分:0)

你可以尝试:

$entity_items_array = array();
$entity_restrict = 'User';
$entity_items = array(0 => 0, 1 => 1, 2 => 2, 3 => 3); 

print_r(array_fill_keys(array($entity_restrict), $entity_items));

只是另一种方法。

答案 1 :(得分:0)

您发布的代码似乎有效。我拿了它并复制了它并得到了它:

$entity_items_array = array();
$entity_restrict = 'User';
$entity_items = array(0 => 0, 1 => 1, 2 => 2, 3 => 3); 

$entity_items_array[$entity_restrict] = $entity_items;

print_r($entity_items_array);

输出这个:

Array
(
    [User] => Array
    (
        [0] => 0
        [1] => 1
        [2] => 2
        [3] => 3
    )
)