简体   繁体   中英

Create new array using values from multidimensional array sharing values

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 (ie:

array[138] {
    127
    47
    13
    56
}

Any help would be awesome. Thank you.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM