0

I have this multidimensional array:

array {
  [0]=>
  array(2) {
    [“foo”]=>
    int(138)
    [“bar”]=>
    int(127)
  }
  [1]=>
  array(2) {
    [“foo”]=>
    int(138)
    [“bar”]=>
    int(47)
  }
  [2]=>
  array(2) {
    [“foo”]=>
    int(138)
    [“bar”]=>
    int(13)
  }
  [3]=>
  array(2) {
    [“foo”]=>
    int(138)
    [“bar”]=>
    int(56)
  }
  [4]=>
  array(2) {
    [“foo”]=>
    int(154)
    [“bar”]=>
    int(77)
  }
  [5]=>
  array(2) {
    [“foo”]=>
    int(154)
    [“bar”]=>
    int(69)
  }
  [6]=>
  array(2) {
    [“foo”]=>
    int(154)
    [“bar”]=>
    int(70)
  }
  [7]=>
  array(2) {
    [“foo”]=>
    int(154)
    [“bar”]=>
    int(75)

For every value of foo that's the same, I want to create a new array with 'foo' being the $key and each of its corresponding 'bar' values in that array (i.e:

array[138] {
    127
    47
    13
    56
}

Any help would be awesome. Thank you.

JohnSchaum
  • 88
  • 8

1 Answers1

0

Well, this is just looping through arrays. I don't really get where is the problem.

$new =array();
for($i=0; $i<count($array); $i++) {
    if(!isset($new[$array[$i]["foo"]]))    //Check for existence of "foo" stack
      $new[$array[$i]["foo"]] = array();   //Create new array, where "bar"s will be put in
    $new[$array[$i]["foo"]][] = $array[$i]["bar"];  //Put "bar" in corresponding "foo" stack
}

You may even use foreach in this case, I avoided it, to make code example friendly to ocassion change.
Because the OP states that the code does not work (which is lie), I made an example.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • It works indeed. You are unbeliavably lazy to even check your code, instead you lie. I now regret that I even tried to help you. [Here](http://u8.8u.cz//crap/arraylooper1.php) is the proof of it. It uses exacly the same code as I posted here. – Tomáš Zato Feb 15 '13 at 23:32
  • Relax, I'm not lying, I used this and it didn't work. Double and triple checked it. I tried closing the if statement after the following line, that didn't work. I tried closing it after the two following lines, that didn't work. I appreciate the help, but I'm only getting one 'bar' value for each 'foo' – JohnSchaum Feb 16 '13 at 00:06
  • But it is not **this** what does not work, but your code. You've had to see it working on my page. So, if you are really sure your code is ok (which is unlikely to be true), make another question about it. Unaccepting this and saying that my code does not work is not likely to help you. – Tomáš Zato Feb 16 '13 at 00:08
  • Fair, I'll give you the check of approval – JohnSchaum Feb 16 '13 at 00:10