使数组唯一并显示其重复的子项

时间:2014-10-06 02:18:13

标签: php arrays

 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()。我怎样才能获得如下输出:

  • 纳拉英格阿尔
    • pulchowk
    • sahidchowk
    • lionschowk

所以那个'narayangarh'是父母和' pulchowk' sahidchowk'和' lionschowk'是孩子。我无法通过正常的foreach循环实现。是否可以通过{{1}}。

1 个答案:

答案 0 :(得分:0)

让我们假装你的城市目前存储在名为$ a的数组中。

  1. 创建其他数组或映射$ b
  2. 循环浏览$ a
  3. 将a->地点附加到b [c_id] - >地点
  4. 您的城市现在处于缩写形式的变量$ b
  5. 例如

    $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代码块