PHP通过每次循环迭代向数组添加键值

时间:2014-11-14 15:13:38

标签: php foreach

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

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

4 个答案:

答案 0 :(得分:2)

这样做:

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

}

答案 1 :(得分:2)

可以使用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);
}

答案 2 :(得分:1)

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

取决于期望的结果......

答案 3 :(得分:1)

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

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

全部取决于您是否要保存在数组中。