PHP 数组。使用 array_push() 将 "$key" => "$value" 对插入数组;
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8685378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP arrays. inserting "$key" => "$value" pair into array with array_push();
提问by Patrick
Why won't this work?
为什么这行不通?
$slidetotal=1;
$slideids = array();
while ($rowcs = mysql_fetch_array($orig_slides_result)) {
$key = $slidetotal;
array_push($slideids[$key], $rowcs['id']);
$slidetotal++;
}
I get this error: [phpBB Debug] PHP Notice: in file ///*.php on line 161: array_push() [function.array-push]: First argument should be an array
我收到这个错误:[phpBB Debug] PHP Notice: in file ///*.php 第 161 行:array_push() [function.array-push]:第一个参数应该是一个数组
Although someone has commented you can do this on this page: http://php.net/manual/en/function.array-push.php, (find: "to insert a "$key" => "$value" pair into an array")
虽然有人评论你可以在这个页面上做到这一点: http://php.net/manual/en/function.array-push.php, (find: "to insert a "$key" => "$value" pair成一个数组")
What is the next best way to insert a list of single values into a php array? By the way, I really can't believe it's hard to find something on this with google.com. Seriously?
将单个值列表插入 php 数组的下一个最佳方法是什么?顺便说一句,我真的不敢相信在 google.com 上很难找到有关此内容的内容。严重地?
回答by Tim Cooper
That PHP.net comment is incorrect. That is pushing $rowcs['id']
onto the array $slideids[$key]
, not the array $slideids
.
那个 PHP.net 评论是不正确的。那是推$rowcs['id']
到阵列上$slideids[$key]
,而不是阵列上$slideids
。
You should be doing the following, in place of your array_push()
call:
您应该执行以下操作来代替您的array_push()
电话:
$slideids[$key] = $rowcs['id'];
回答by osoner
Why don't you do;
你为什么不这样做;
$slidetotal=1;
$slideids = array();
while ($rowcs = mysql_fetch_array($orig_slides_result)) {
$slideids[$slidetotal] = $rowcs['id'];
$slidetotal++;
}
Also you can do like below if you don't need the key to start from 1;
如果您不需要从 1 开始的密钥,您也可以像下面这样做;
$slideids = array();
while ($rowcs = mysql_fetch_array($orig_slides_result)) {
$slideids[] = $rowcs['id'];
}
回答by Mr. BeatMasta
ummm hard-searching will work for google I think :) anyway, error tells you everything you need to know. that means first argument of array_push is not an array, you give a single value (string) to array_push ($slideids[$key]). Also why do you need to use array_push in php? I'd rather use
嗯,我认为硬搜索将适用于 google :) 无论如何,错误会告诉您您需要知道的一切。这意味着 array_push 的第一个参数不是数组,你给 array_push ($slideids[$key]) 一个值(字符串)。另外为什么需要在php中使用array_push?我宁愿用
$slideids[] = $rowcs['id'];
and what you're trying to do is:
而你想要做的是:
$slideids[$key] = $rowcs['id'];
i guess...
我猜...