[英]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: 对于相同的foo的每个值,我想创建一个新数组,其中'foo'是$ key以及该数组中每个对应的'bar'值(即:
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. 在这种情况下,甚至可以避免使用foreach来使代码示例易于更改。
Because the OP states that the code does not work (which is lie ), I made an example . 因为OP指出代码无效(这是lie ), 所以我举了一个例子 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.