PHP新手求助:如何向数组的对象属性中追加多个对象
解决循环中向已存在店铺的鞋子列表追加对象的问题
看起来你已经走对了大部分路,问题出在数组的值传递特性上——你通过searchForId拿到的$store是原数组中元素的副本,修改它并不会影响$stores里的原始数据。下面给你两种可行的解决方案:
方案一:修改searchForId返回索引(推荐)
把searchForId从返回数组本身改成返回该元素在$stores中的索引,这样就能直接操作原数组的元素了:
首先更新你的搜索函数:
function searchForId($id, $array) { foreach ($array as $key => $val) { if ($val['storeId'] === $id) { return $key; // 返回索引而非数组副本 } } return null; }
然后调整循环逻辑:
foreach($product->shoes as $shoe) { $storeKey = searchForId($shoe->storeId, $stores); if($storeKey === null){ // 店铺不存在,创建新的店铺数组并添加第一只鞋 $store = array( 'storeId' => $shoe->storeId, 'store' => $shoe->store, 'showAll' => false, 'shoes' => [$shoe] ); array_push($stores, $store); } else { // 直接通过索引向原数组的shoes列表追加新鞋 $stores[$storeKey]['shoes'][] = $shoe; } }
方案二:不修改搜索函数,用引用遍历原数组
如果你不想改动searchForId,可以在else块里通过引用遍历$stores,找到对应店铺后直接修改:
foreach($product->shoes as $shoe) { $store = searchForId($shoe->storeId, $stores); if($store === null){ $store = array( 'storeId' => $shoe->storeId, 'store' => $shoe->store, 'showAll' => false, 'shoes' => [] ); $store['shoes'][] = $shoe; array_push($stores, $store); } else { // 用&引用遍历,修改$existingStore就是修改原数组的元素 foreach ($stores as &$existingStore) { if ($existingStore['storeId'] === $shoe->storeId) { $existingStore['shoes'][] = $shoe; break; // 找到后立即退出循环,提升效率 } } // 注意:用完引用后最好unset掉,避免后续意外修改 unset($existingStore); } }
小提示
你一开始把shoes初始化为new \stdClass,后来改成空数组[]是完全正确的——因为要存储多个鞋对象,数组才是合适的容器,对象没法直接用[]语法追加元素。
内容的提问来源于stack exchange,提问作者nash63
相关产品推荐
相关产品推荐

