将数组元素移动到同一数组中的另一个元素中

时间:2015-12-22 13:50:38

标签: php arrays sorting

这是我的阵列:

array (size=5)
  0 => 
    object(stdClass)[50]
      public 'PkID' => string '608' (length=3)
      public 'ConstructionTypeFk' => string '1' (length=1)
      public 'Price' => string '65757' (length=5)
      public 'discount_id' => string '0' (length=1)
  3 => 
    object(stdClass)[53]
      public 'PkID' => null
      public 'ConstructionTypeFk' => string '2' (length=1)
      public 'Price' => null
      public 'discount_id' => null
  4 => 
    object(stdClass)[54]
      public 'PkID' => null
      public 'ConstructionTypeFk' => string '1' (length=1)
      public 'Price' => null
      public 'discount_id' => 2

我想移动在共享相同元素内共享discount_id的每个元素共享相同的ConstructionTypeFk。所以在这种情况下,第一个元素和数组下面的最后一个元素看起来像这样:

array (size=5)
  0 => 
    object(stdClass)[50]
      public 'PkID' => string '608' (length=3)
      public 'ConstructionTypeFk' => string '1' (length=1)
      public 'Price' => string '65757' (length=5)
      public 'discount_id' => string '0' (length=1)
      public 'discount' => 
         array (size=1)
           0 => 
              object(stdClass)[54]
                public 'PkID' => null
                public 'ConstructionTypeFk' => string '1' (length=1)
                public 'Price' => null
                public 'discount_id' => 2
           1 => 
              another one if needed etc... 
  3 => 
    object(stdClass)[53]
      public 'PkID' => null
      public 'ConstructionTypeFk' => string '2' (length=1)
      public 'Price' => null
      public 'discount_id' => null

到目前为止,我有这段代码($query包含我的原始数组):

    foreach ($query as $key => $value)
    {
        if ($value->discount_id !== '0' || $value->discount_id !== NULL)
        {

            //Move this element to another element here!
            $query['index of the element that has the same ConstructionTypeFk']->discount[] = $value;
        }
        else
        {
            continue;
        }
    }

    return $result;

如何获得“具有相同ConstructionTypeFk的元素索引”?或者有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

$result = [];
foreach ($array as $item) {
    if (!$item->discount_id) {
        $result[] = $item;
    } else {
        foreach ($result as $parent) {
            if ($item->ConstructionTypeFk == $parent->ConstructionTypeFk) {
                $parent->discount[] = $item;
            }
        }
    }
}

不是最高性能的解决方案,但非常直接。