1

I have this set of data that I get from html form. It is basically a multidimensional array.

Data

array(3) {
  ["r1"]=>
  array(2) {
    [0]=>
    string(1) "2"
    [1]=>
    string(1) "4"
  }
  ["r2"]=>
  array(2) {
    [0]=>
    string(1) "5"
    [1]=>
    string(2) "96"
  }
  ["tekma_id"]=>
  array(2) {
    [0]=>
    string(1) "7"
    [1]=>
    string(1) "8"
  }
}

Problem: What i want to do, is to go over this array and for each iteration create a data variable(array).

So for example:

First iteration:

$data = array(
   'r1' => '2'
   'r2' => '5'
   'tekma_id' => '7'
)

Second iteration:

$data = array(
   'r1' => '4'
   'r2' => '96'
   'tekma_id' => '8'
)

I've tried with this:

foreach ($data as $key => $value) {
    foreach ($value as $index => $v) {
        echo "<br>";
        echo "r1: $v";
        echo "<br>";
        echo "r2: $v";
        echo "<br>";
        echo "tekma_id: $v";
    }
}

But it didn't work. Sorry for my bad english and thanks for any help. Cheers!

2
  • Are r1, r2 and tekma_id fixed or dynamic indexes? Commented Sep 13, 2013 at 10:10
  • @hjpotter92 they come from inputs with names r1[], r2[] and tekma_id[] Commented Sep 13, 2013 at 10:11

2 Answers 2

6

How about this?

$array = array(
    'r1' => array(2, 4),
    'r2' => array(5, 96),
    'tekma_id' => array(7, 8));

$keys = array_keys($data);
$iterations = count($array[$keys[0]]);

for($i = 0; $i < $iterations; $i++) {
    $data = array();
    foreach($array as $key => $value) {
        $data[$key] = $value[$i];
    }
    print_r($data);
}

Output:

Array
(
    [r1] => 2
    [r2] => 5
    [tekma_id] => 7
)
Array
(
    [r1] => 4
    [r2] => 96
    [tekma_id] => 8
)
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

$keys = array_keys($data);
$count = count(array_shift(array_values($data)));

for ($i = 0; $i<$count; $i++) {
    $result = array();
    foreach ($keys as $key) {
        $result[$key] = $data[$key][$i];
    }
    var_dump($result);
}

1 Comment

+1 Just one note - in strict mode, array_shift() will throw an error in this case since the argument is not a variable.

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.