1

I have a multidimensional array like this coming from an POST;

array(4) { 
   ["id"]=> array(3) { 
        [0]=> string(1) "4" 
        [1]=> string(1) "5" 
        [2]=> string(1) "6" 
      } 
   ["deliverer"]=> array(3) { 
        [0]=> string(13) "x" 
        [1]=> string(12) "y" 
        [2]=> string(5) "z" 
      } 
   ["num_users"]=> array(3) { 
        [0]=> string(2) "10" 
        [1]=> string(2) "10" 
        [2]=> string(1) "5" 
      } 
   ["ADD"]=> string(6) "FORWARD" 
      } 

I would like to associate the ID to the "deliverer" and the "num_users" in order to update a table in MySQL. I've tried both this way:

foreach ($_POST as $data){
    var_dump($data);
  }

and

foreach ($_POST as $key=>$value){
    var_dump($value);
  }

But in both cases I ain't going in the right direction. I ain't so skilled so I wish to have some tips on how to proceed correctly.

Kind regards,

Chris

3
  • What kind of array would you like to have at the end ? Could you give us an example ? Commented Dec 2, 2014 at 11:58
  • Sure, array('id'=>'value', 'deliverer'=>'value', 'num_users'=>'value') for every index present in the multidimensional array. Cheers and thanks in advance. Commented Dec 2, 2014 at 12:04
  • 1
    Take a look at php.net/manual/en/function.array-column.php — it does exactly what you want. Commented Dec 2, 2014 at 12:10

2 Answers 2

1
$ids = $_POST['id'];
$deliverer = array();
$num_users = array();
$num_usersRaw = $_POST['num_users'];
$i=0;
foreach ($_POST['deliverer'] as $k=>$v) {
  $id = $ids[$i];
  $deliverer[$id] = $v;
  $num_users[$id] = $num_usersRaw[$i];
  ++$i;
}

Explanation:

Get all the IDs first.

This will serve as the keys for deliverer and num_rows arrays.

Loop over $_POST['deliverer'] and then assign key values to the two arrays: $deliverer and $num_users.

Sign up to request clarification or add additional context in comments.

1 Comment

Plus 1 for the explanation.
0

Here is a potentital solution, depending on what you want in the end.

$datas = array();
foreach ($_POST['id'] as $k => $id) {
  $datas[] = array("id" => $id, "deliverer" => $_POST['deliverer'][$k], "num_users" => $_POST['num_users'][$k]);
}

An "easier to understand" solution would be :

$datas = array();
foreach ($_POST['id'] as $k => $id) {
  $datas[$k]['id'] = $id; // or $_POST['id'][$k]
  $datas[$k]['deliverer'] = $_POST['deliverer'][$k];
  $datas[$k]['num_users'] = $_POST['num_users'][$k];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.