使用多维数组共享值中的值创建新数组 [英] Create new array using values from multidimensional array sharing values
问题描述
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) 您甚至可以在这种情况下使用foreach,我避免它,使代码ex充分友好的变化。 I have this multidimensional array: 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: Any help would be awesome. Thank you. Well, this is just looping through arrays. I don't really get where is the problem. You may even use foreach in this case, I avoided it, to make code example friendly to ocassion change. 这篇关于使用多维数组共享值中的值创建新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ 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堆栈
因为OP声明代码不起作用(这是谎言</ strong>),我做了个例子。 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)
array[138] {
127
47
13
56
}
$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
}
Because the OP states that the code does not work (which is lie), I made an example.