我有变量$related
女巫是stdCalss对象,我想用一个foreach循环转换为reffrence数组。
Var_dump
的 $related
:
array (size=19)
0 =>
object(stdClass)[20]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1567' (length=4)
1 =>
object(stdClass)[21]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1562' (length=4)
2 =>
object(stdClass)[22]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1564' (length=4)
3 =>
object(stdClass)[23]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1410' (length=4)
4 =>
object(stdClass)[24]
public 'id_product' => string '111' (length=3)
public 'related' => string '77' (length=2)
5 =>
object(stdClass)[25]
public 'id_product' => string '111' (length=3)
public 'related' => string '1610' (length=4)
Php代码:
foreach ($related AS $r){
????
}
var_dump($rels);
希望输出:
$rels = array(
'1568'=>'1567, 1562, 1564, 1410',
'111'=>'77,1610'
);
答案 0 :(得分:1)
$rels = array ();
foreach ($related as $r){
$rels[$r->id_product] .= $r->related . ","; // put all of them with respective key together
}
$rels = array_map(
function ($a) {
$a = preg_replace('~,(?!.*,)~', '', $a);
return $a;
}
,$rels); // remove last commas
var_dump($rels);
答案 1 :(得分:1)
尝试,
$rels = array();
foreach($related as $r){
$rels[$r->id_product] .= $r->related.', ';
}
array_walk_recursive($related, function(&$item){
$item = rtrim($item,', ');
});
来自PHP文档:http://php.net/manual/en/language.types.type-juggling.php
答案 2 :(得分:1)
构建一个临时数组并将其内爆:
foreach($related AS $r) {
$temp[$r->id_product][] = $r->related;
$rels[$r->id_product] = implode(', ', $temp[$r->id_product]);
}
print_r($rels);