array (size=3)
0 =>
object(stdClass)[20]
public 'id' => string '12' (length=2)
public 'cities' => string 'narayangarh' (length=11)
public 'c_id' => string '24' (length=2)
public 'places' => string 'pulchowk' (length=8)
1 =>
object(stdClass)[21]
public 'id' => string '13' (length=2)
public 'cities' => string 'narayangarh' (length=11)
public 'c_id' => string '24' (length=2)
public 'places' => string 'sahidchowk' (length=10)
2 =>
object(stdClass)[22]
public 'id' => string '14' (length=2)
public 'cities' => string 'narayangarh' (length=11)
public 'c_id' => string '24' (length=2)
public 'places' => string ' lionschowk' (length=11)
在这个数组中,有一个共同cities
"narayangarh",具有共同的'c_id'
重复三次,并且有不同的'places'
具有不同的'id'
。如何获得以下输出:
- 纳拉扬格尔
- 普尔乔克
- 萨希德霍克
- 莱昂肖克
因此,"narayangarh"是父母,"pulchowk","sahidchowk"和"lionschowk"是孩子。我无法通过正常的 foreach 循环实现。通过array_unique()
有可能吗.
假设您的城市当前存储在名为 $a 的数组中。
- 创建其他数组或映射$b
- 循环$a
- 将 a->place 附加到 b[c_id]->位置
- 您的城市现在处于可变$b浓缩形式
例如。
$b = array();
foreach ($a as $city) {
// If city already is in "$b"
if ( array_key_exists($city->c_id, $b) ) {
array_push($b[$city->c_id]->places, $city->places);
} else {
$b[$city->c_id] = $city;
$b[$city->c_id]->places = array($city->places);
}
}
var_dump($b);
array (size=1)
0 =>
object(stdClass)[20]
public 'id' => string '12' (length=2)
public 'cities' => string 'narayangarh' (length=11)
public 'c_id' => string '24' (length=2)
public 'places' => array (size=3)
0=> string 'pulchowk' (length=8)
1=> string 'sahidchowk' (length=10)
2=> string 'lionschowk' (length=11)
编辑:$b[$city]改为$b[$city->c_id] array_key_exists代码块与 else 代码块交换