Home > Enterprise >  Yii2 merge arrays
Yii2 merge arrays

Time:02-21

I need merge arrays for json API. I have 3 requests:

$data['winners'] = Winners::find()->limit(8)->all();

$user = User::findIdentity($value->user_id);

$product = Products::find()->localized($lang)->where(['coupon' => $value->coupon])->one();

I need foreach all $data['winners'], get User with id from $data['winners'], and get Product from $data['winners']. After i need merge in 1 json all my data.

I try like this:

$data['winners'] = Winners::find()->limit(8)->all();
        foreach ($data['winners'] as $value){
            $user = User::findIdentity($value->user_id);
            $product = Products::find()->localized($lang)->where(['coupon' => $value->coupon])->one();
            $result = ArrayHelper::merge($product, $user);
        }

CodePudding user response:

If i understand correctly you question you need an array with all the $data[winners] istances and foreach instance merge the related Produce and User then you could use

 $result[] = array_merge($value, $product, $user);

.

    $data['winners'] = Winners::find()->limit(8)->all();
    foreach ($data['winners'] as $value){
        $user = User::findIdentity($value->user_id);
        $product = Products::find()->localized($lang)->where(['coupon' => $value->coupon])->one();
        $result[] = array_merge($value, $product, $user);
    }

CodePudding user response:

I found solution:

$winners = Winners::find()->limit(8)->all();
        $i = 0;
        foreach ($winners as $value){
            $user = User::findIdentity($value->user_id);
            $product = Products::find()->localized($lang)->where(['coupon' => $value->coupon])->one();
            $data[$i]['image'] = $product->prize_image;
            $data[$i]['user'] = $user->firstname.' '.$user->lastname;
            $data[$i]['title'] = $product->win_title;
            $i  ;
        }
        return $data;
  • Related