1

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';

Leonardo
  • 2,439
  • 33
  • 17
  • 31
  • Does this answer your question? [How to convert an array to object in PHP?](https://stackoverflow.com/questions/1869091/how-to-convert-an-array-to-object-in-php) – pringi Jan 10 '22 at 14:00

3 Answers3

0

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]
0

Simple you can get array by following code

$resultsInitial->toArray();
0

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.

Sevan
  • 669
  • 1
  • 5
  • 18