[英]php pushing into an array within a loop
I'm generating an array of results within a loop, and I want to add to the array within the loop. 我正在循环内生成结果数组,我想在循环内添加到数组。 Obviously array push will not work as these are key, value pairs.
显然,数组推将不起作用,因为它们是键,值对。
foreach($res as $ap){
$this->db->where('event_time >', $ev_time);
$this->db->where('event_ID', $ap['event_id']);
$query = $this->db->get('events');
if($query->num_rows() > 0){
$result = $query->result_array();
$linked[] = $result[0]; // <-- want to add key, value pair within this
$linked['new_key'] = $new_value; // <-- did not work :(
}
}
How can I do this? 我怎样才能做到这一点?
Also this array later gets merged with another array. 同样,此数组稍后会与另一个数组合并。 If I add an extra key, value pair to this that isn't in the other array, will that break the merge?
如果我添加一个不在另一个数组中的额外键,值对,这会破坏合并吗?
foreach($res as $ap){
$this->db->where('event_time >', $ev_time);
$this->db->where('event_ID', $ap['event_id']);
$query = $this->db->get('events');
if($query->num_rows() > 0){
$result = $query->result_array();
$linked[] = $result[0]; // <-- want to add key, value pair within this
$linked['new_key'][] = $new_value;
}
}
Try this 尝试这个
$i = 0;
foreach($res as $ap){
$this->db->where('event_time >', $ev_time);
$this->db->where('event_ID', $ap['event_id']);
$query = $this->db->get('events');
if($query->num_rows() > 0){
$result = $query->result_array();
$linked[$i] = $result[0]; // <-- want to add key, value pair within this
$linked[$i]['new_key'] = $new_value;
$i++;
}
}
The $i
will enable you to add the new value into the same element as the $result[0]
was was written to. $i
将使您可以将新值添加到写入$result[0]
的相同元素中。
也许尝试类似:
$myarray[] = array($key, $value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.