使用多维数组共享值中的值创建新数组 [英] Create new array using values from multidimensional array sharing values

查看:122
本文介绍了使用多维数组共享值中的值创建新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个多维数组:

  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)

对于foo的每个值都是相同的,我想创建一个新的数组,其中'foo'是$ key和数组中相应的'bar'值(即:

 数组[138] {
127
47
13
56
}

任何帮助都很棒,谢谢。

解决方案

(b)
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $($)$ $ i = 0; $ i< count($ array); $ i ++){
if(!isset($ new [$ array [$ i] [foo]])//检查是否存在foostack
$ new [$ array [$ i] [foo]] = array(); //创建新的数组,其中bar将放在
$ new [ $ array [$ i] [foo]] [] = $ array [$ i] [bar]; //将bar放入相应的foo堆栈

您甚至可以在这种情况下使用foreach,我避免它,使代码ex充分友好的变化。

因为OP声明代码不起作用(这是谎言<​​/ strong>),我做了个例子

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.

解决方案

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.

这篇关于使用多维数组共享值中的值创建新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆