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'
不同array_unique()
。我怎样才能获得如下输出:
所以那个'narayangarh'是父母和' pulchowk' sahidchowk'和' lionschowk'是孩子。我无法通过正常的foreach循环实现。是否可以通过{{1}}。
答案 0 :(得分:0)
让我们假装你的城市目前存储在名为$ a的数组中。
例如
$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] swapped array_key_exists代码块与else代码块