PHP在每次循环迭代中向数组添加键值
我有一个数组,我想从中创建一个具有键值对的新数组。我想我知道需要什么,我只是需要一些语法方面的帮助PHP在每次循环迭代中向数组添加键值,php,foreach,Php,Foreach,我有一个数组,我想从中创建一个具有键值对的新数组。我想我知道需要什么,我只是需要一些语法方面的帮助 foreach ($stuff as $thing){ $thing1 = $thing->prop1; $thing2 = $thing->prop2; // this is where I need to set $newstuff = array($thing1 => $thing2); $newstuff[] = ?? } 这样做: fo
foreach ($stuff as $thing){
$thing1 = $thing->prop1;
$thing2 = $thing->prop2;
// this is where I need to set $newstuff = array($thing1 => $thing2);
$newstuff[] = ??
}
这样做:
foreach ($stuff as $thing){
$thing1 = $thing->prop1;
$thing2 = $thing->prop2;
// this is where I need to set $newstuff = array($thing1 => $thing2);
$newstuff[$thing1] = $thing2;
}
或
取决于期望的结果
$newstuff = array();
foreach ($stuff in $thing) {
$newstuff[$thing->prop1] = $thing->prop2;
}
或
这一切都取决于是否要保存在数组中。可以使用array\u map()
而不是foreach()
。例如:
$newstuff = array_map(function($v){return array($v->prop1=>$v->prop2);}, $stuff);
并使用foreach()
:
$newstuff = array();
foreach ($stuff in $thing) {
$newstuff[$thing->prop1] = $thing->prop2;
}
$newstuff = array();
foreach ($stuff in $thing) {
$newstuff[] = array($thing->prop1, $thing->prop2);
}
$newstuff = array_map(function($v){return array($v->prop1=>$v->prop2);}, $stuff);
foreach ($stuff as $thing){
$newstuff[] = array($thing->prop1=>$thing->prop2);
}