Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP在每次循环迭代中向数组添加键值_Php_Foreach - Fatal编程技术网

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);
}