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.

2
  • 1
    you can do it using foreach using some logic :) Commented Feb 15, 2013 at 21:12
  • I'm new to this... ^ such as? Commented Feb 15, 2013 at 23:17

1 Answer 1

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.

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

4 Comments

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 is the proof of it. It uses exacly the same code as I posted here.
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'
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.
Fair, I'll give you the check of approval

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.