Linundus Ondu Linundus Ondu - 1 year ago 52
PHP Question

Foreach multidimensional array in php

I have these input data that i stored in array before inserting into database.

$regData = array (
'user_type' => $_SESSION['user']->user_type,
'user_id' => $_SESSION['user']->id,
'child_id' => $this->input->post('child_name[]'),
'tc_id' => $this->input->post('tc_id'),
'tc_sources' => $this->input->post('tc_sources'),
'tc_created_date' => date('Y-m-d H:i:s'),
);


The output for
$regData
in array :

Array
(
[user_type] => parent
[user_id] => 5
[child_id] => Array
(
[0] => 47
[1] => 49
)

[tc_id] => 11
[tc_sources] => Email
[tc_created_date] => 2017-07-26 21:56:57
)


I am trying to
foreach
the array to make sure that it can be inserted into different row in the table as follow :

foreach ($regData as $k) {
foreach ($k as $val) {
$newArr[] = array(
'user_type' => $val['user_type'],
'user_id' => $val['user_id'],
'child_id' => $val['child_id'],
'tc_id' => $val['tc_id'],
'tc_sources' => $val['tc_sources'],
'tc_created_date' => $val['tc_created_date'],
);
}
}


EDIT

This is the output of the array form that I want, but the data all having the same value, I don't really know how to foreach the array to get the exact data after loop :

Array
(
[0] => Array
(
[user_type] => 4
[user_id] => 4
[child_id] => 4
[tc_id] => 4
[tc_sources] => 4
[tc_created_date] => 4
)

[1] => Array
(
[user_type] => 4
[user_id] => 4
[child_id] => 4
[tc_id] => 4
[tc_sources] => 4
[tc_created_date] => 4
)

)

Answer Source

Please try below code,

if(!empty($regData['child_id'])) {
    foreach($regData['child_id'] as $key => $row) {
       $newArr[$key]['user_type'] = $regData['user_type'];
       $newArr[$key]['user_id'] = $regData['user_id'];
       $newArr[$key]['child_id'] = $row;
       $newArr[$key]['tc_id'] = $regData['tc_id'];
       $newArr[$key]['tc_sources'] = $regData['tc_sources'];
       $newArr[$key]['tc_created_date'] = $regData['tc_created_date'];
   }
}

Output is below,

Array
(
  [0] => Array
    (
        [user_type] => parent
        [user_id] => 5
        [child_id] => 47
        [tc_id] => 11
        [tc_sources] => Email
        [tc_created_date] => 2017-07-26 16:27:49
    )

  [1] => Array
    (
        [user_type] => parent
        [user_id] => 5
        [child_id] => 49
        [tc_id] => 11
        [tc_sources] => Email
        [tc_created_date] => 2017-07-26 16:27:49
    )

)

Do you get output above? if it is not, please describe your question and sample output by comment.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download