Search code examples
phparraysjsonmongodbphp-mongodb

Json array to array


I have an JSON array from laravel like this:

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => Array
                (
                    [_id] => MongoDB\BSON\ObjectID Object
                        (
                            [oid] => 5a15e52b5bd98b7a0040fac8
                        )

                    [UnitPrice] => 18
                    [UnitsInStock] => 39
                )

            [1] => Array
                (
                    [_id] => MongoDB\BSON\ObjectID Object
                        (
                            [oid] => 5a15e52b5bd98b7a0040fac9
                        )

                    [UnitPrice] => 19
                    [UnitsInStock] => 17
                )

            [2] => Array
                (
                    [_id] => MongoDB\BSON\ObjectID Object
                        (
                            [oid] => 5a15e52b5bd98b7a0040faca
                        )

                    [UnitPrice] => 10
                    [UnitsInStock] => 13
                )

        )

)

How can I take only the UnitPrice and the UnitsInStock as an array? Is there any way without using a loop?

I want to use it like this:

...

->dataset('UnitPrice', [5,20,100,...]) // array's values = [5,20,100,...]

->dataset('UnitsInStock', [52,120,100,...]) // array's values = [52,120,100,...]

Solution

  • Laravel has a lists method to get array for a given column. Otherwise, you can use the array_column method of PHP.

    $unitPrices = array_column($items, 'UnitPrice');