如何在php中使用foreach循环创建多维数组



输入数组

$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$job   = $_POST['job'];
$desc  = $_POST['desc'];
$photo = $_POST['image_url'];
$memberdata = Array(
          'first_name' => $fname,
          'last_name' => $lname,
          'job' => $job,
          'desc' => $desc,
          'image_url' => $photo
          );

并回显它打印的数组,如下所示。应该如何修改代码以实现目标?还有其他方法可以达到我想要的效果吗?成员表单是使用jquery动态生成的。我想要得到下面提到的数组的成员。

Array
(
    [first_name] => Array
        (
            [0] => Member1
            [1] => Member2
            [2] => Member3
        )
    [last_name] => Array
        (
            [0] => Member1
            [1] => Member2
            [2] => Member3
        )
    [job] => Array
        (
            [0] => President
            [1] => MD
            [2] => CEO
        )
    [desc] => Array
        (
            [0] => President of
            [1] => MD of
            [2] => CEO of
        )
    [image_url] => Array
        (
            [0] => 
            [1] => 
            [2] => 
        )
)

如何使特定的数组从上面的数组?应该如何修改代码以实现目标?这就是我想要的。

 Array
(
   [0] => Array
   (
      [first_name] => Member1
      [last_name] => Member1
      [job] => President
      [desc] => President of
      [image_url] =>
   )
   [1] => Array
   (
      [first_name] => Member2
      [last_name] => Member2
      [job] => MD
      [desc] => MD of
      [image_url] =>
   )
   [2] => Array
   (
      [first_name] => Member3
      [last_name] => Member3
      [job] => CEO 
      [desc] => CEO of
      [image_url] =>
   )
)

我猜你的foreach循环是这样的:

$result = array();
foreach($members as $member) {
    $result['firstname'][] = $member['firstname'];
    $result['last_name'][] = $member['last_name'];
    //etc
}

应该是这样的:

$result = array();
foreach($members as $member) {
    $result[] = array(
        'firstname' => $member['firstname'],
        'last_name' => $member['last_name'],
        'job' => $member['job'],
        'desc' => $member['desc'],
        'image_url' => $member['image_url']
    );
}

基于示例代码的更新:

POST字段是数组,因此您必须确保每个成员的所有字段都被发布,因为for循环基于具有相同数量值的所有字段。

$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$job   = $_POST['job'];
$desc  = $_POST['desc'];
$photo = $_POST['image_url'];
$memberdata = array();
// we iterate the firstname field and access the same indexes from the other fields. The $i starts with 0 and gets incremented until it iterated over all the firstnames
for($i = 0; $i < count($fname); $i++) {
    $memberdata[] = array(
        'first_name' => $fname[$i], // we access the firstname at the current index
        'last_name' => $lname[$i],
        'job' => $job[$i],
        'desc' => $desc[$i],
        'image_url' => $photo[$i]
    );
}
var_dump($memberdata);

相关内容

  • 没有找到相关文章