skip to Main Content

beginner Question :
I have query like this :

 $arr1 = BillProduct::where('bill_id', '=', $bill->id)->get('quantity'); 
 $arr2 = BillProduct::where('bill_id', '=', $bill->id)->get('product_id');

and its return like this :

[[{"quantity":15}], [[{"product_id":2}]

how can i get just digit like 15, 2 ??
and how get in foreach next to each other? like

15,2
18,3

return in 2 variable like :

return $arr1, $Arr2;

3

Answers


  1. You can do

    if ($arr1->isNotEmpty()) {
        $quantity = $arr1->first()->quantity; 
        echo $quantity; // Output: 15
    } 
    

    If multiple use foreach loop. Ex

    $quantities = [];
    foreach ($arr1 as $item) {
        $quantities[] = $item->quantity;
    }
    print_r($quantities);
    

    Edit 01

    $arr1 = BillProduct::where('bill_id', '=', $bill->id)->pluck('quantity');
    $arr2 = BillProduct::where('bill_id', '=', $bill->id)->pluck('product_id');
    
    $result = [];
    
    foreach ($arr1 as $index => $quantity) {
        $product_id = $arr2[$index];
        $result[] = [$quantity, $product_id];
    }
    
    print_r($result);
    
    Login or Signup to reply.
  2. Merge columns of two array

    Starting from PHP 5, it is possible to merge the columns of two associative arrays using the array_replace_recursive() function.

    • To achieve this, the result of these two Eloquent queries – Collection class – needs to be converted into an array. –> Can use toArray()
    $arr1 = BillProduct::select('quantity')->where('bill_id', '=', $bill->id)->get()->toArray();
    $arr2 = BillProduct::select('product_id')->where('bill_id', '=', $bill->id)->get()->toArray();
    
    $result = array_replace_recursive($arr1, $arr2);
    /*
    Result:
    
    [
      ["quantity" => 15, "product_id" => 2],
      ["quantity" => 18, "product_id" => 3],
      ...
    ]
    */
    
    foreach ($result as $record) {
      $quantity = $record['quantity'];
      $product_id = $record['product_id'];
      // ...
    }
    

    More information: https://www.php.net/manual/en/function.array-replace-recursive.php

    Login or Signup to reply.
  3. Assuming your product_id does not appear multiple times in the result, you can use the second argument to pluck() to assign another column as the key:

    $result = BillProduct::where('bill_id', $bill->id)->pluck('quantity', 'product_id'); 
    foreach($result as $productId => $quantity) {
        // enjoy life
    }
    

    You save one query now 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search