PHP 在每次循环迭代时将键值添加到数组中


PHP add key value to array with each loop iteration

>我有一个数组,我想从中创建一个带有键值对的新数组。我想我知道需要什么,我只需要一些语法方面的帮助。

foreach ($stuff as $thing){
    $thing1 = $thing->prop1;
    $thing2 = $thing->prop2;
    // this is where I need to set $newstuff = array($thing1 => $thing2);
    $newstuff[] = ??
}

可以使用 array_map() 代替 foreach() 。例:

$newstuff = array_map(function($v){return array($v->prop1=>$v->prop2);}, $stuff);

并使用foreach()

foreach ($stuff as $thing){
    $newstuff[] = array($thing->prop1=>$thing->prop2);
}

这样做:

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 as $thing){
    $thing1 = $thing->prop1;
    $thing2 = $thing->prop2;
    // this is where I need to set $newstuff = array($thing1 => $thing2);
    $newstuff[] = array($thing1 => $thing2);
}

$newstuff = array();
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; 
}

$newstuff = array();
foreach ($stuff in $thing) {
   $newstuff[] = array($thing->prop1, $thing->prop2); 
}

一切都取决于您是否要保存在数组中。