Convert data array at php laravel

Viewed 55

I have data array :

Array
(
  [0] => Illuminate\Support\Collection Object
    (
      [items:protected] => Array
        (
          [0] => stdClass Object
            (
              [product_id] => 780
            )

          [1] => stdClass Object
            (
              [product_id] => 789
            )

          [2] => stdClass Object
            (
              [product_id] => 800
            )

          [3] => stdClass Object
            (
              [product_id] => 769
            )
        )
     )  
)

How can I get data only value on array?
output needed $data = '780','789','800','769';

3 Answers

I Am Supposing You Are fetching this data from your database using Equolent ORM.

So First Fetch the data:

$resultsInitial = Model::get(); // you can specify your clauses here

then create a new empty array

$results = [];

then run a foreach to push the data into the new array

foreach ($resultsInitial as $record) {
   array_push($results, $record->product_id);
}

then finally return the new array

return $results; // output: [1,2,3]

Simple you can get array by following code

$resultsInitial->toArray();

implode method solves your issue. A sample is mentioned in the below code block.

$collection = collect([
    ['account_id' => 1, 'product' => 'Desk'],
    ['account_id' => 2, 'product' => 'Chair'],
]);

$collection->implode('product', ', ');

// Desk, Chair

For detailed information take a look implode at the Laravel documentation.

If you would like to have output as an array so you should use the pluck method. The same example is explained below.

$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
]);

$plucked = $collection->pluck('name');

$plucked->all();

// ['Desk', 'Chair']

For detailed information take a look pluck at the Laravel documentation.

Related