手动创建关联数组 [英] Manually creating an associative array

查看:79
本文介绍了手动创建关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个具有动态数据的关联数组,并且遇到了一些麻烦。

I'm trying to create an associative array with dynamic data, and having some trouble.

我想生成一个如下所示的数组

I'd like to produce an array that looks like the following while fetching rows from a MySQL query.

Array
(
  [0] = Array
  (
    [name] => First
  )
  [1] = Array
  (
    [name] => Second
  )
  [2] = Array
  (
    [name] => Third
  )
  [3] = Array
  (
    [name] => Fourth
  )
  [4] = Array
  (
    [name] => Fifth
  )
)

我一直在尝试使用array_merge,但是它没有给我想要的结果。显然,Array_merge在foreach内部的操作与在外部的操作不同(我在有和没有循环的情况下都运行了相同的代码,没有按照我需要的方式运行)。

I've been trying to use array_merge, but it's not giving me the result I want. Array_merge apparently doesn't operate the same inside a foreach as it does outside (I ran the same code with and without the loop, without worked the way I need).

基本上,这就是我目前正在做的(不起作用):

Basically, this is what I'm doing currently (which doesn't work):

foreach($idList as $id)
{
    $arr[] = array_merge(array(), array('name' => $id));
}

这给了我这样的输出:

Array
(
    [0] = Array
    (
        [name] => first
    )
    [1] = Array
    (
        [0] = Array
        (
            [name] => first
        )
        [name] => second
    )
    [2] = Array
    (
        [0] = Array
        (
            [name] => first
        )
        [1] = Array
        (
            [0] = Array
            (
                [name] => first
            )
            [name] => second
        )
        [name] => third
    )
)


推荐答案

您在这里遇到了一些问题。

You've got a few issues here.

主要是,您不能两次拥有相同的索引。 名称只能是一次索引,因此不可能期望输出。

Mainly, you can't have the same index twice. 'name' can be the index once and only once, so you're 'desired' output is impossible.

此外,该语句还很成问题

Also, this statement is pretty problematic

foreach($idList as $id)
{
    $arr[] = array_merge(array(), array('name' => $id));
}

使用$ arr [] = $ x就像是推动。它将在数组的后面添加一个新元素,并对其进行数字索引。

The use of $arr[] = $x is like a push. It adds a new element to the back of the array, numerically indexed.

您不需要使用array_merge。 array_merge返回合并在第一个参数上的第二个参数。您只是想添加一个新元素。另外,这就是您使用的行还是使用的 array_merge($ arr,array('name'=> $ id)); ???

Your use of array_merge is unnecessary. array_merge returns the second argument merged over the first argument. You are just trying to add a single new element. Also, is that exactly the line you used or did you use array_merge($arr, array('name' => $id)); ???

尝试:

foreach($idList as $id)
{
    $arr[] = array('name' => $id);
}

您将获得:

Array
(
    [0] = Array
    (
        [name] => first
    )
    [1] = Array
    (
        [name] => second
    }
 ....

以此类推。我不确定这是否正是您想要的,但是您最初提出的建议是不可能的。

And so on. I'm not sure if this is exactly what you want, but what you proposed in the first place isn't possible.

这篇关于手动创建关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆