Nehal Shah Nehal Shah - 3 months ago 10
PHP Question

how to create multidimensional array using a foreach loop in php?

When I take the form values in 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
);


and echoing this array it prints like below.
How should the code be modified to achieve the goal?
Is there any other ways to get results what I want?
Member forms are dynamically generated using jquery.
And I want to get member vise array that I mentioned below.

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

)


How to make particular array from above array?
How should the code be modified to achieve the goal?
This is what i want.

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

Answer

My guess is your foreach loop looks like this:

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

And it should be something like this:

$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']
    );
}

Update based on sample code:

The POST fields are arrays, so you have to make sure all fields are posted for every member, as the for loop is based on all fields having the same amount of values.

$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);
Comments