0

Hi I am using laravel and I Have a array this array has keys that some of them are string I want to Change them to int and all of them going to be int

$nativeContent = NativeContent::find($id);
$nativeContentView = $nativeContent->countViewNative()
            ->orderBy('created_at', 'ASC')
            ->get()
            ->groupBy(function($date) {
               return Carbon::parse($date->created_at)->format('m'); // grouping by months
            });

and my array is like this enter image description here

7
  • In PHP, "02" == 2 is true, as its a weakly-typed language. You can treat strings-values of integers as integers if you really need to. Commented May 14, 2019 at 6:00
  • Try using array_values(). Something like: $newArray = array_values($oldArray); Commented May 14, 2019 at 6:00
  • @Magnus Eriksson it gives me this error array_values() expects parameter 1 to be array, object given Commented May 14, 2019 at 6:03
  • @Hassan it needs to be $nativeContentView = array_values($nativeContentView); Commented May 14, 2019 at 6:04
  • 1
    That's because it's a collection object. Turn it into an array first: array_values($collection->toArray()) Commented May 14, 2019 at 6:04

2 Answers 2

1

Try this:

->groupBy(function($date) {
            return intval(Carbon::parse($date->created_at)->format('m')); // grouping by months
        });
Sign up to request clarification or add additional context in comments.

Comments

0

If you have a collection, that could be easily achieved, with:

$newListWithIntKeys = $nativeContentView->values();

This will use a regular sequential integer, starting from 0 to N, instead of your named keys.

Verified in Laravel 10

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.