开发者

Multidimensional array and PHP

Why doesn't this work:

$counter = 0;
  foreac开发者_如何学运维h($projects as $project) {
    $list[$counter]['id'] = $project['id'];
    $list[$counter]['name'] = $project['name'];
    $counter++;
  }
}

I would like to create a multidimensional array where the data is stored in the i'th element (via the iteration). The data gets overwritten; everything seems to be stored in $list[0] for some reason (while $projects contains 2 elements). I've first tried this:

foreach($projects as $project) {
  $list[]['id'] = $project['id'];
  $list[]['name'] = $project['name'];
  }
}

But this doesn't work either. How to do this? The array is created at the start: $list = new array();


The easiest way would be:

foreach($projects as $project) {
    $list[] = array('id' => $project['id'], 
                    'name' => $project['name']);
}

But the first example looks 'ok'. You could try initializing the array beforehand:

foreach($projects as $project) {
    $list[$counter] = array();
    $list[$counter]['id'] = $project['id'];
    $list[$counter]['name'] = $project['name'];
    $counter++;
}


In this example, you are trying to access $list[$counter] which isn't set, thus $list[$counter][$id] is not valid. You need to first define $list[$counter] to be an array. Either by $list[$counter] = array(); or you could do $list[] = array('id' => $project['id'];

Correct way

$counter = 0;
foreach($projects as $project) {
    $list[$counter] = array();
    $list[$counter]['id'] = $project['id'];
    $list[$counter++]['name'] = $project['name'];
}

Easier way

foreach($projects as $project) {
    $list[] = array(
        'id' => $project['id'],
        'name' => $project['name'],
    );
}

Easiest way (without definition of the content in $projects) This may or may not be suited to the task, but will produce the same results given that $projects does not contain any unwanted data.

foreach($projects as $project) 
{
    $list[] = $project;
}

Or

$list = array_values($projects);

If $projects somehow contains unwanted data and filtering of data is wanted, the following line will also make do.

$list = array_values(array_map('array_intersect_key',$projects,array_pad(array(),count($projects),array_flip(array('id','name')))));


$list[] will add an element every time it is called, so in your (second) example two times in one iteration.

foreach($projects as $project) {
  $list[] = array(
     'id' => $project['id'],
     'name' = $project['name');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜