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] = Arra开发者_如何学Pythony
(
[name] => Fifth
)
)
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));
}
This gives me output like this:
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));
}
The use of $arr[] = $x is like a push. It adds a new element to the back of the array, numerically indexed.
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));
???
Try:
foreach($idList as $id)
{
$arr[] = array('name' => $id);
}
And you will get:
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.
精彩评论