Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
    
Are r1, r2 and tekma_id fixed or dynamic indexes? –  hjpotter92 Sep 13 '13 at 10:10
    
@hjpotter92 they come from inputs with names r1[], r2[] and tekma_id[] –  intelis Sep 13 '13 at 10:11

2 Answers 2

up vote 4 down vote accepted

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
)
share|improve this answer
    
that worked like a charm, thank you sir –  intelis Sep 13 '13 at 10:20

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);
}
share|improve this answer
1  
+1 Just one note - in strict mode, array_shift() will throw an error in this case since the argument is not a variable. –  Boaz Sep 13 '13 at 13:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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