0

Actual array as below is basically the array of $_POST. One can understand what is coming from the form. three controls with same name different value. What i need is below this array.

Array
(
    [mytext] => Array
        (
            [0] => aaaa
            [1] => bbbb
            [2] => ddd
        )

    [mysel] => Array
        (
            [0] => one
            [1] => two
            [2] => two
        )

    [submit] => Submit
)

I need the array in row format below but be dynamic based of $_POST data.

Array
(
    [0] => Array
        (
            [0] => aaaa
            [1] => one

        )

    [1] => Array
        (
            [0] => bbbb
            [1] => two

        )

    [2] => Array
        (
            [0] => dddd
            [1] => two

        )


)

3 Answers 3

1

Try this:

$out = Array();
foreach($_POST['mytext'] as $k=>$v) {
    $out[$k] = Array($v,$_POST['mysel'][$k]);
}
var_dump($out);
1
// Code To Get controls value in row wise
$count=0;
foreach($_POST as  $key=>$val){
    foreach($_POST[$key] as $val2){
        $row[$count][]=$val2;
        $count++;
    }
    $count=0;
}
print_r($row);
3
  • I have solved in the way above.. any more good suggestions and examples to do in better way.
    – mbkazi
    May 16, 2012 at 5:33
  • Just an FYI, you can use $val instead of $_POST[$key]. You might also want to check if $val is an array, so it ignores submit.
    – gen_Eric
    May 16, 2012 at 13:49
  • good to hear, without the check of array works fine, ignores submit if not an array. Yes it could be $val
    – mbkazi
    May 18, 2012 at 11:47
0

Loop through one of the fields, and then pull the corresponding value from the other field.

$result = array();
foreach($_POST['mytext'] as $k=>$v){
    $result[] = array($v, $_POST['mysel'][$k]);
}

You can also use array_map to do this:

// PHP 5.3+
$result = array_map(function($a, $b){
    return array($a, $b);
}, $_POST['mytext'], $_POST['mysel']);

// PHP <= 5.2
$result = array_map(create_function('$a,$b', 'return array($a,$b);'), $_POST['mytext'], $_POST['mysel']);
3
  • can you explain your code how does this works. I am understanding partially.
    – mbkazi
    May 16, 2012 at 5:29
  • What if more than two elements from post
    – mbkazi
    May 16, 2012 at 5:30
  • The first code block is simple. It loops over one array, and uses the key to find the corresponding value in the other array(s). array_map is a bit different. You can pass as many arrays as you want to array_map, and it then calls the callback function for each element in each array. So, to add 3 arrays do array_map(function($a,$b,$c){},$a1,$a2,$a3);.
    – gen_Eric
    May 16, 2012 at 13:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.