我正在使用array_push
将元素添加到特定key
位置的数组中,请检查我的代码:
foreach($query as $key)
{
$appointment['id_services'] = array_push($appointment,$key['id_services']);
}
print_r($appointment['id_services']);
现在$query
在我的例子中包含两个数组,我遍历$query
变量并取两个id_services
,返回的值是:14
和13
。不管怎样,当我打印appointment['id_services]
数组索引时,我得到了:16
,但为什么?它应该在appointment['id_services]
中创建另一个具有以下结构的数组:
[0] => 14
[1] => 13
我需要推送元素而不是覆盖它。
我做错了什么?
我认为您不需要将它分配给任何东西。这只是一个函数调用:
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>
有关详细信息,请参阅手册。。
您还可以使用[]
运算符向数组追加(推送)。只需这样做:
foreach ( $query as $key )
$appointment['id_services'][] = $key['id_services'];
print_r( $appointment['id_services'] );
这将把$key['id_services']
的值推送到$appointment['id_services']
阵列。
或者,使用array_push
(返回阵列的新大小):
foreach ( $query as $key )
array_push( $appointment['id_services'], $key['id_services'] );