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

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

问题描述:

This is my array:

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

I want to move every element that has discount_id assigned inside coresponding element that shares the same ConstructionTypeFk. So in this case the last element under the first element and array would look like so:

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

So far I have this code ($query contains my original array):

    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;

How can I get "index of element the that has the same ConstructionTypeFk"? Or is there a better way?

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

Not the most performant solution, but pretty straight forward.