我似乎很难理解array
的工作原理。结果,我无法解决这个问题。
foreach($results as $key => $value){
$product_key = array(
'key' => $key
);
array_push($results, $product_key);
}
var_dump($results); exit;
预期输出
array(2) {
[0]=>
object(stdClass)#21 (4) {
["items_id"]=>
string(1) "1"
["item_name"]=>
string(6) "laptop"
["price"]=>
string(5) "20000"
["quantity"]=>
string(2) "10"
["key"]=>
int(0)
}
[1]=>
object(stdClass)#22 (4) {
["items_id"]=>
string(1) "2"
["item_name"]=>
string(10) "smartphone"
["price"]=>
string(5) "10000"
["quantity"]=>
string(3) "200"
["key"]=>
int(1)
}
意外输出
array(4) {
[0]=>
object(stdClass)#21 (4) {
["items_id"]=>
string(1) "1"
["item_name"]=>
string(6) "laptop"
["price"]=>
string(5) "20000"
["quantity"]=>
string(2) "10"
}
[1]=>
object(stdClass)#22 (4) {
["items_id"]=>
string(1) "2"
["item_name"]=>
string(10) "smartphone"
["price"]=>
string(5) "10000"
["quantity"]=>
string(3) "200"
}
[2]=>
array(1) {
["key"]=>
int(0)
}
[3]=>
array(1) {
["key"]=>
int(1)
}
}
答案 0 :(得分:2)
您将新值(即数组)推送到存在数组的末尾,您期望什么呢?
如果要修改当前的interated数组值,请使用以下方法:
foreach($results as $key => $value) {
// use `->` as `$value` is object
$value->key = $key;
}
var_dump($results); exit;