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

时间:2016-08-31 13:11:11

标签: php arrays multidimensional-array

当我在数组

中获取表单值时
$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动态生成成员表单。 我想获得我在下面提到的成员vise数组。

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] =>
   )
)

1 个答案:

答案 0 :(得分:6)

我的猜测是你的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);