开发者

add a key value in an array

开发者 https://www.devze.com 2023-03-19 14:10 出处:网络
I have $test = array(); if(isset($ln[8])){ $test[] .= $id[0].\'=>\'.$ln[14]; } But itputs the array like this

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 d开发者_如何学编程o this

array (
           6525 => 120
           6521 => 1243
           5214 => 1674
           6528 => 155
)

How would I do that.


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:

$test[$id[0]] = $ln[14];

Note how I treat $id[0] as the key to the $test array. It could have been the integer 6265, a string with value "hello", a variable called $key, a function call, or in this case an element from another array.


You want to make the $id[0] the index, whereas currently you are concatenating a string together as the value.

Try the following:

$test[$id[0]] = $ln[14];

I'd also encourage you to look at CakePHP's Set Class.


Try this

$test[$id[0]] = $ln[14];

Your mistake is that you try to append a string to the array and you have to use the id as a key and the ln as a value.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号