Как отформатировать json массив объектов в люменах? - PullRequest
1 голос
/ 07 января 2020

Я написал API, используя люмен, ниже мой код.

public function customerslist(Request $request)
{
    $allTransactions = UserTransaction::where('marchant_id','=',$request->marchant_id)->get();

    foreach ($allTransactions as  $allTransaction) {
        $rows['response']="success";
        $rows['message']="Transaction";
        $customer_name = MarchantUser::where('id','=',$allTransaction->customer_id)->first();
        $response['customer_id'] = $allTransaction->customer_id;
        $response['customer_name'] = $customer_name->contact_name;
        $response['customer_ph'] = $customer_name->user_mobile_number;
        $response['customer_img'] = '';
        $response['trans_amount'] = $allTransaction->amount;
        $response['transaction_type'] = $allTransaction->transaction_type;
        $response['date']=date("d-M-Y:h:m:a",strtotime($allTransaction->created_at));
        $transaction['customer_data'][]=$response;
        $rows['customer_list']=$transaction;
    }
    echo json_encode($rows);
}

с кодом выше я получаю результат следующим образом:

{
    "response": "success",
    "message": "Transaction",
    "customer_list": {
        "customer_data": [
            {
                "customer_id": "4",
                "customer_name": "anjan",
                "customer_ph": "8120653256",
                "customer_img": "",
                "trans_amount": "2000",
                "transaction_type": "debit",
                "date": "04-Jan-2020:09:01:am"
            },
            {
                "customer_id": "4",
                "customer_name": "anjan",
                "customer_ph": "8120653256",
                "customer_img": "",
                "trans_amount": "2000",
                "transaction_type": "credit",
                "date": "04-Jan-2020:10:01:am"
            },
            {
                "customer_id": "4",
                "customer_name": "anjan",
                "customer_ph": "8120653256",
                "customer_img": "",
                "trans_amount": "2000",
                "transaction_type": "credit",
                "date": "04-Jan-2020:10:01:am"
            },
            {
                "customer_id": "5",
                "customer_name": "users",
                "customer_ph": "8120653256",
                "customer_img": "",
                "trans_amount": "4000",
                "transaction_type": "debit",
                "date": "04-Jan-2020:09:01:am"
            },
            {
                "customer_id": "6",
                "customer_name": "Ganesh Ji",
                "customer_ph": "8120653250",
                "customer_img": "",
                "trans_amount": "2000",
                "transaction_type": "debit",
                "date": "06-Jan-2020:10:01:am"
            }
        ]
    }
}

Но мой ожидаемый результат должен выглядеть как

  {
    "response": "success",
    "customer_list": [
      {
        "date": "04-Jan-2020",
        "customer_data": [
          {
            "customer_id": "4",
            "customer_name": "Rahul",
            "customer_img": "",
            "customer_ph": "763783438",
            "transaction_amount": "2000",
            "transaction_type": "debit"
          },
          {
            "customer_id": "4",
            "customer_name": "Anjan",
            "customer_img": "",
            "customer_ph": "57656765",
            "transaction_amount": "2000",
            "transaction_type": "advance"
          }
        ]
      },

      {
        "date": "06-01-2020",
        "customer_data": [
          {
            "customer_id": "6",
            "customer_name": "Ganesh Ji",
            "customer_img": "",
            "customer_ph": "763783438",
            "transaction_amount": "4000",
            "transaction_type": "debit"
          }
    ]
  }

Список клиентов должен иметь другой объект массива в зависимости от даты транзакции. Я пытался использовать group by, но group by не работает в люмене. Как создать объект массива json на основе отдельной даты.

1 Ответ

0 голосов
/ 07 января 2020

изменить $transaction['customer_data'][] на $transaction[]['customer_data']. но если вы хотите сделать date таким, вы должны сначала создать массив слияния. ниже приведен полный код:

public function customerslist(Request $request)
{
    $allTransactions = UserTransaction::where('marchant_id', '=', $request->marchant_id)->get();

    foreach ($allTransactions as $allTransaction) {

        $customer_name                = MarchantUser::where('id', '=',
            $allTransaction->customer_id)->first();
        $response['customer_id']      = $allTransaction->customer_id;
        $response['customer_name']    = $customer_name->contact_name;
        $response['customer_ph']      = $customer_name->user_mobile_number;
        $response['customer_img']     = '';
        $response['trans_amount']     = $allTransaction->amount;
        $response['transaction_type'] = $allTransaction->transaction_type;
        $temp['date']                 = date("d-M-Y:h:m:a",
            strtotime($allTransaction->created_at));
        $temp["customer_data"]        = $response;
        $transaction[]                = $temp;
    }
    $rows['response']      = "success";
    $rows['message']       = "Transaction";
    $rows['customer_list'] = $transaction;

    return $rows;
}

btw $rows должен быть размещен снаружи foreach, потому что его нужно установить только один раз, и без json_encode он автоматически кодируется, если вы используете return

...