在数组中添加一个键值
我有
$test = array();
if(isset($ln[8])){
$test[] .= $id[0].'=>'.$ln[14];
}
但是它像这样放置数组
array (
[0]=> 6525 => 120
[1]=> 6521 => 1243
[2]=> 5214 => 1674
[3]=> 6528 => 155
)
,而我希望它这样做
array (
6525 => 120
6521 => 1243
5214 => 1674
6528 => 155
)
我会怎么做。
I have
$test = array();
if(isset($ln[8])){
$test[] .= $id[0].'=>'.$ln[14];
}
But it puts the array like this
array (
[0]=> 6525 => 120
[1]=> 6521 => 1243
[2]=> 5214 => 1674
[3]=> 6528 => 155
)
whereas I want it to do this
array (
6525 => 120
6521 => 1243
5214 => 1674
6528 => 155
)
How would I do that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在做的是将一个字符串添加到数组中的每个元素,例如“6525 => 120”。您真正想要做的是将 $lan[14] 中的值(例如整数值 120)添加到位置 $id[0](例如 6525)。这是使用常规数组语法执行此操作的方法:
请注意我如何将
$id[0]
视为$test
数组的键。它可能是整数6265
、值为"hello"
的字符串、名为$key
的变量、函数调用,或者在此区分另一个数组中的元素。What you are doing is adding a string consisting of, e.g., "6525 => 120" to each element in the array. What you really want to do is add the value from $lan[14] (e.g., the integer value 120) to the position $id[0] (e.g., 6525). This is how you do that with regular array syntax:
Note how I treat
$id[0]
as the key to the$test
array. It could have been the integer6265
, a string with value"hello"
, a variable called$key
, a function call, or in this case an element from another array.您希望将
$id[0]
作为索引,而当前您正在将一个字符串连接在一起作为值。尝试以下操作:
我还鼓励您查看CakePHP 的 Set 类。
You want to make the
$id[0]
the index, whereas currently you are concatenating a string together as the value.Try the following:
I'd also encourage you to look at CakePHP's Set Class.
试试这个
您的错误是您尝试将字符串附加到数组中,并且必须使用 id 作为键,使用 ln 作为值。
Try this
Your mistake is that you try to append a string to the array and you have to use the
id
as a key and theln
as a value.