ACF fields in submenu page of custom post type

I’ve established a custom post type named “Dealers,”. Among them, there’s a distinct dealer with unique fields and a dedicated page. Although it falls under the category of dealers, I prefer to manage this dealer’s page within the section of the custom post type.

That’s why I’ve created a submenu page within this custom post type. Here, I want to add the appropriate ACF fields.

Below is how I created my custom post type:

<?php
/**
 * Custom posttype
 */
function vivafloors_custom_posttype_dealer()
{
    $dealersSlug = 'dealers';

    if (is_array(get_field('dealers', 'option'))) {
        $dealersSlug = get_field('dealers', 'option')['dealers_slug'];
    }

    $dealersName = ucfirst($dealersSlug);

    $labels = array(
        'name' => _x($dealersName, 'Post Type General Name', 'vivafloors'),
        'singular_name' => _x('Dealer', 'Post Type Singular Name', 'vivafloors'),
        'menu_name' => __('Dealers', 'vivafloors'),
        'name_admin_bar' => __('Dealer', 'vivafloors'),
        // 'parent_item_colon' => __('Hoofd case:', 'vivafloors'),
        'all_items' => __('Alle dealers', 'vivafloors'),
        'add_new_item' => __('Nieuwe dealer', 'vivafloors'),
        'add_new' => __('Nieuwe dealer', 'vivafloors'),
        'new_item' => __('Nieuwe dealer', 'vivafloors'),
        'edit_item' => __('Dealer bewerken', 'vivafloors'),
        'update_item' => __('Wijzig dealer', 'vivafloors'),
        'view_item' => __('Bekijk dealer', 'vivafloors'),
        'search_items' => __('Zoek dealer', 'vivafloors'),
        'not_found' => __('Not found', 'vivafloors'),
        'not_found_in_trash' => __('Not found in Trash', 'vivafloors'),
    );
    $rewrite = array(
        'slug' => $dealersSlug,
        'with_front' => true,
        'pages' => true,
        'feeds' => true,
    );
    $args = array(
        'label' => __('dealer', 'vivafloors'),
        'description' => __('Dealers', 'vivafloors'),
        'labels' => $labels,
        'supports' => array('title', 'revisions', 'thumbnail', 'revisions'),
        'hierarchical' => true,
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'menu_position' => 20,
        'menu_icon' => 'dashicons-store',
        'show_in_admin_bar' => true,
        'show_in_nav_menus' => true,
        'can_export' => true,
        'has_archive' => false,
        'exclude_from_search' => false,
        'publicly_queryable' => true,
        'rewrite' => $rewrite
    );
    register_post_type('dealer', $args);
    register_taxonomy('dealer_category','dealer', array('hierarchical' => true, 'label' => 'Categories', 'query_var' => true, 'rewrite' => true)); 
}

// Hook into the 'init' action
add_action('init', 'vivafloors_custom_posttype_dealer', 0);

And this is how I create a submenu page within this custom post type:

function add_custom_page_to_menu() {
    add_submenu_page(
        'edit.php?post_type=dealer',
        __('Dealer Vivafloors', 'text_domain'),
        __('Dealer Vivafloors', 'text_domain'),
        'edit_posts', 
        'dealer-vivafloors',
        'call_back_function'
    );
}
add_action('admin_menu', 'add_custom_page_to_menu');

function call_back_function() {
    ?>
    <h1>Hello</h1>
    <?php
}

I’m encountering difficulty in showcasing ACF fields on the submenu page. Is the recommended approach to manage this through ACF fields? I’ve been unable to find a method to connect this submenu page with ACF fields. Or do I need to trigger something within the call_back_function?

Any ideas?

Forming a tree structure from HTML elements in an array [closed]

I see an implementation here via a recursive function, but..

I’ve tried dozens of times to compose this function, but I can’t get my head around the logic by which it should work, although at first glance it shouldn’t be so difficult. I seem to understand the points where the exit from the recursive function should occur, but it doesn’t give me anything.

I would like to understand the algorithm how it should work, in any language, perhaps at least in words, because so far I have not been able to “text” even mentally formulate what the solution should look like.

I want to implement a function to generate the resulting array in the format I need.
I have prepared the data, input and output, so that it is clearer to you what I want to achieve.

INPUT

$input = ['h1', 'p', 'h2', 'p', 'p', 'h3', 'p', 'h2', 'p', 'h3', 'p', 'h1', 'p', 'h2', 'p', 'h3', 'p'];

OUTPUT

$output = [
    [
        'title' => 'h1',
        'descriptions' => ['p'],
        'childrens' => [
            [
                'title' => 'h2',
                'descriptions' => ['p', 'p'],
                'childrens' => [
                    [
                        'title' => 'h3',
                        'descriptions' => ['p'],
                    ],
                ]
            ],
            [
                'title' => 'h2',
                'descriptions' => ['p'],
                'childrens' => [
                    [
                        'title' => 'h3',
                        'descriptions' => ['p']
                    ]
                ]
            ]
        ]
    ],
    [
        'title' => 'h1',
        'descriptions' => ['p'],
        'childrens' => [
            [
                'title' => 'h2',
                'descriptions' => ['p'],
                'childrens' => [
                    [
                        'title' => 'h3',
                        'descriptions' => ['p']
                    ]
                ]
            ]
        ]
    ]
];

my (not working) implementation:

function parseDOM(array $inputArray): array {
    $output = [];
    $position = 0;
    $domElementsQuantity = count($inputArray);
    $parentTagLvl = 0;

    function getCurrentTagLvl(string $node): bool|int
    {
        return match ($node) {
            'h1' => 1,
            'h2' => 2,
            'h3' => 3,
            'h4' => 4,
            'h5' => 5,
            'h6' => 6,
            default => false,
        };
    }


    function recursiveCreateTree(array $inputArray, int &$offsetIndex, $parentTagLvl) {
        $tree = [];
        $arrayItemsQuantity = count($inputArray);

        while ($offsetIndex <= $arrayItemsQuantity) {
            $currentNode = $inputArray[$offsetIndex];
            $currentTagLvl = getCurrentTagLvl($currentNode);

            if ($currentTagLvl !== false && $currentTagLvl < $parentTagLvl) {
                return $tree;
            }

            if ($currentTagLvl === false) {
                $tree['descriptions'][] = $currentNode;
            } else {
                $tree['title'] = $currentNode;
                $tree['childrens'] = recursiveCreateTree($inputArray, $offsetIndex, $currentTagLvl);
            }


            $offsetIndex++;
        }

        return $tree;
    }

    while ($position <= $domElementsQuantity) {
        $currentNode = $inputArray[$position];
        $currentTagLvl = getCurrentTagLvl($currentNode);

        if ($currentTagLvl === false) {

        }
        else {

            if ($currentTagLvl > $parentTagLvl) {
            }
            else {
                $parentTagLvl = $currentTagLvl - 1;
            }
        }

    }


    return $output;
}

To display the results:

echo '<pre>';
print_r(parseDOM($input));

​Different Server Environments Different Results With php-qrcode-detector-decoder

I am using php-qrcode-detector-decoder for reading QR codes in photos. It works on most servers, PHP 7.3 – 8.3.

But on some other servers I get errors and I can not figure out why. Even with the same PHP version.

It seems that the ones that work are cPanel hosted and the ones that don’t are not, at least so far.

The error is: 

PHP Fatal error:  Uncaught Error: Object of class GdImage could not be converted to string in /path/to/GDLuminanceSource.php:54

​Line 54 is:

$this->$gdImage = $gdImage;

Comes from:

public function GDLuminanceSource($gdImage, $width, $height)
{
    parent::__construct($width, $height);

    $this->dataWidth = $width;
    $this->dataHeight = $height;
    $this->left = 0;
    $this->top = 0;
    $this->$gdImage = $gdImage;

​Any insight on why it works in one environment and not another?

I’ve tried changing $this->$gdImage = $gdImage; to $this->gdImage = $gdImage; but makes it not work on the working servers.

pagination for attachments page in wordpress

I have a piece of code for showing wordpress attachments. this code shows latest 40 attachments in the page but I want to add pagination for this code.
code:

    $args = array( 'post_type'  => 'attachment',
        'post_mime_type' => 'image',
             'post_status'    => 'inherit',
     'orderby' => 'date',
         'order' => 'DESC',
    'post__not_in'=>array($post->ID),
            'posts_per_page' => 40,
            'tax_query' => $tax_query );

    // finally run the query
    $loop = new WP_Query($args);

    if( $loop->have_posts() ) {

    ?>
          
<div class="masonry-items">
  <ul class="grid effect-2" id="grid">
    <?php while( $loop->have_posts() ) : $loop->the_post(); ?> 
           <li class="item">
      <div class="thumb">
      <a class="relative" href="<?php echo get_attachment_link( $image->ID ); ?>">
           <?php echo wp_get_attachment_image($image->ID, $size = 'thumbnail'); ?>
            <div class="caption absolute">
               <p>
                   <?php  echo wp_get_attachment_caption(get_post_thumbnail_id()); ?>
               </p>
             </div>
           </a>            
      </div>
    </li>
       <?php 
        endwhile;
    }
    wp_reset_query();
?>

How to change customers shipping zone using PHP in WooCommerce?

How can I change customers shipping zone in WooCommerce to a different zone if the customer is admin for example?

Let’s say that I have 2 shipping zones that both have same region. I would want one shipping zone for customers that aren’t admin and the other one would be for admin users.

I have tried to use different Woocommerce hooks in PHP to change the shipping zone, but I haven’t been able to. I have no idea how could I change the shipping zone through code.

It would be helpful if someone could show me an example of how to change customers shipping zone using PHP.

Google API key issue in PHP with text to speech

I have a php file in which I am trying to make a function where I pass in text for the Google cloud API to return me a text to speech file.
text-to-speech.php

<?php

require_once __DIR__ . '/vendor/autoload.php';

class TextToSpeech
{   
    public function TextToSpeech(array $input)
    {
        $apiKey = 'mykey';
        $text = $input; 
        $languageCode = 'lv-LV'; 
        $audioEncoding = GoogleCloudTextToSpeechV1AudioEncoding::MP3; 

        try {

            $client = new GoogleCloudTextToSpeechV1TextToSpeechClient(['credentials' => $apiKey]);


            $synthesisInput = (new GoogleCloudTextToSpeechV1SynthesisInput())
                ->setText($text);

            $voice = (new GoogleCloudTextToSpeechV1VoiceSelectionParams())
                ->setLanguageCode($languageCode)
                ->setSsmlGender(GoogleCloudTextToSpeechV1SsmlVoiceGender::FEMALE); 

           
            $audioConfig = (new GoogleCloudTextToSpeechV1AudioConfig())
                ->setAudioEncoding($audioEncoding);

            
            $response = $client->synthesizeSpeech($synthesisInput, $voice, $audioConfig);

            
            file_put_contents('output.mp3', $response->getAudioContent());

            echo 'Audio file saved successfully.';
        } catch (Exception $e) {
            echo 'Error: ' . $e->getMessage();
        }
    }
}
?>

Front-page.php

...
$test = new TextToSpeech;
$test->TextToSpeech(["Hello my name is BingBong"]);
...

composer.json

...
"google/cloud" : "^0.229",
...

Error: Could not find keyfile: mykey

This is the only error I have not been able to fix. Where I have written mykey is my actual API key and I removed all the possible restrictions I could find on their website, but it still doesn’t want to work

I tried other ways of passing my API key in the hopes that it would recognise it, but it didn’t. This is my first time working with an API, so I don’t really know how else I could fix this issue.

Getting HTML in input on select in jquery ui autocomplete

I am using jquery ui autocomplete to fetch cars,parts,and services from my database, i am diffrentiating both or three records type by adding span in last. But when i select any value its showing span html code in input with code how can i fix that ?

php:

public function partCodeAutoc(Request $request)
{
        $return_arr1 = [];
        $return_arr2 = [];
        $return_arr3 = [];
        $type = $request->code_type;
        $part_code = $request->term;
        $column = "code";
        $column2 = "car_code";

        $query = Cars::where($column2, "LIKE", "%" . $part_code . "%")->where('car_status',3)->get();
        if ($query->count() > 0) {
            foreach ($query as $rows) {
                $newdata = $rows->$column2.' <span class="badge badge-light-secondary" style="float:right;">Car</span>';
                array_push($return_arr1, $newdata);
            }
        $return_arr2 = array_unique($return_arr1);
        foreach ($return_arr2 as $key => $value) {
            $row_array["label"] = $value;
            $row_array["value"] = $value;
            array_push($return_arr3, $row_array);
        }
        echo json_encode($return_arr3);
}

js:

$("#part_code").autocomplete({
    source: function (request, response) {
      if ($("#service-chk").is(":checked")) code_type = 1; 
      else code_type = 0;
      $.ajax({
        url: "partCodeAutoC",
        type: "POST",
        dataType: "json", 
        data: {
          code_type:code_type,
          term: request.term,
        },
        success: function (data) {
          response(data);
          },
      });
    },
    minLength: 1,
    select: function (event, ui) {

    },
}).data("ui-autocomplete")._renderItem = function (ul, item) {
    return $("<li>")
        .append("<div>" + item.label + "</div>")
        .appendTo(ul);
};

Capturing Referring Affiliate Details in WP Affiliate Manager

I’m using the WP Affiliate Manager plugin for my WordPress site and I’d like to capture the referring affiliate’s details (name, email, etc.) alongside their referrals. Currently, the plugin only tracks referrals by numbers (1, 2, 3).

I understand this might not be a built-in feature, but I’m hoping to find a solution. Here are some options I’ve considered:

  1. Third-party integrations: Are there any known plugins that integrate with WP Affiliate Manager and allow capturing referring affiliate details?
  2. Alternative approaches: If integrations aren’t available, what are some workarounds to achieve this functionality (e.g., form builders, CRM integration)?

Technical details

WordPress version: Latest
WP Affiliate Manager version: Latest

Desired outcome

I want to associate the referring affiliate’s name and email with each referral recorded in WP Affiliate Manager.

Additional notes

I’m not comfortable with extensive custom development.
Any suggestions or insights on how to achieve this would be greatly appreciated!

I checked the WP Affiliate Manager documentation and settings to see if there was an option to capture referring affiliate details, but I couldn’t find anything.

Using ACF Repeaters, that are using paralaxes

I have created a image and text block within ACF, and there are a bunch of options like switching sides of the text and image, can have a background etc.

The issue i am having, is that because you can duplicate these repeaters within wordpress on the pages, I have a parallax on the block, specifically the image block, and so, if you duplicate the repeater, the parallax obviously is duped also as the repeater is identical.

So when you scroll down, ALL the parallaxes will activate, which does not work as when you scroll down, the parallax blocks will be half way up the page as they are all starting at the same time.

Would there be a way to alter my code, so that the parallax only activates once it enters the viewport, rather than a scroll activation? Having the Paralax contained within it’s own box.

I hope that makes sense

php:

<?php
if ($bgColour == 'yes') : ?>
<div class="bg-primary pseudo-100 py-5 z-n1">
<?php endif; ?>
<div class="row align-items-center">
    <div class="col-12 col-md-6 <?= $directionTxt; ?> <?= $overTxt; ?>"><?= $text; ?>
        <?php
        $link = get_field('button');
        if ($link) :
            $link_url = $link['url'];
            $link_title = $link['title'];
            $link_target = $link['target'] ? $link['target'] : '_self';
        ?>
            <a class="button" href="<?php echo esc_url($link_url); ?>" target="<?php echo esc_attr($link_target); ?>"><?php echo esc_html($link_title); ?></a>
        <?php endif; ?>
    </div>
    <div class="col-12 col-md-6 position-relative <?= $directionImage; ?> <?= $overImg; ?>">
        <div id="parallax-container" data-speed="0.5">
            <div></div>
            <?php if ($backgroundColourBlock == 'yes') : ?>
                <div id="parallax-bg" class="parallax-item"></div>
            <?php endif; ?>
            <div id="middle-image" class="parallax-item"><?= wp_get_attachment_image($imageTwo, 'large'); ?></div>
            <div id="front-image" class="parallax-item"><?= wp_get_attachment_image($imageOne, 'large'); ?></div>
        </div>
    </div>
</div>
<?php
if ($bgColour == 'yes') : ?>
</div>

Javascript:

window.addEventListener('scroll', () => {
let parent =  document.getElementById('parallax-container');
let children = parent.getElementsByTagName('div');
for(let i = 0; i < children.length; i++) {
children[i].style.transform = 'translateY(calc(200px - ' + (window.scrollY * i / 
children.length) + 'px))';
}
}, false)

Google API list reviews – 403 forbidden

I’m trying to implement fetching Google reviews for my business in Laravel using google/apiclient but I keep getting response code 403 Forbidden after my GET request.

        $client = new GoogleClient();
        $serviceAccountKeyFilePath = storage_path('key-json.json');
        $client->setAuthConfig($serviceAccountKeyFilePath);
        $client->addScope('https://www.googleapis.com/auth/business.manage');
        $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');

        $accessToken = $client->fetchAccessTokenWithAssertion();

        if (isset($accessToken['access_token'])) {
            $client->setAccessToken($accessToken['access_token']);
        } else {
            return;
        }


        $clientID = 'my-client-id';
        $placeID = 'my-place-id';

        $httpClient = $client->authorize();
        $url = 'https://mybusiness.googleapis.com/v4/accounts/' . $clientID . '/locations/' . $placeID . '/reviews';

        $response = $httpClient->get($url, [
            'headers' => [
                'Authorization' => 'Bearer ' . $accessToken['access_token'],
                'Accept' => 'application/json',
            ],
        ]);

        dd($response);

I enabled these APIs in my account:

  • My Business Account Management API
  • My Business Business Information API
  • My Business Place Actions API
  • Places API
  • Places API (New)

But still I keep getting this

GuzzleHttpPsr7Response {#1670 ▼
  -reasonPhrase: "Forbidden"
  -statusCode: 403
}

I’m kinda confused and I can’t see what I am missing here.

The DELETE method is not supported for route logout. Supported methods: POST

I want to use the CRUD in my web project, I imported the starter kit breeze to have a CRUD (after the project has been created / bit too late)

Unfortunately I can’t access to the method from the controller I always get redirected to the log out method through another controller AuthenticatedSessionController which call an aother destroy method to logout.

In this case I would my view to call the Profile controller and not the Authenticated Controller and apply the CRUD method

AuthenticatedSessionController :

 public function logout(Request $request): RedirectResponse
    {

        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect('/');
    }

ProfileController : (the one should destroy, edit, etc) :

public function edit(Request $request): View
    {
        return view('profile.edit', [
            'user' => $request->user(),
        ]);
    }

    /**
     * Update the user's profile information.
     */
    public function update(ProfileUpdateRequest $request): RedirectResponse
    {
        $request->user()->fill($request->validated());

        if ($request->user()->isDirty('email')) {
            $request->user()->email_verified_at = null;
        }

        $request->user()->save();

        return Redirect::route('profile.edit')->with('status', 'profile-updated');
    }


    public function destroy(Request $request): RedirectResponse
    {

        $request->validateWithBag('userDeletion', [
            'password' => ['required', 'current_password'],
        ]);

        $user = $request->user();

        Auth::logout();

        $user->delete();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return Redirect::route('/')
            ->with('success', __('messages.user_deleted_successfully'));
    }

My route web.php

Route::middleware('auth')->group(function () {

    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
//    dd('124');
//    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');


});
require __DIR__.'/auth.php';

My route auth.php

  Route::post('logout', [AuthenticatedSessionController::class, 'logout'])
                ->name('logout');

    Route::delete('/profile', [AuthenticatedSessionController::class, 'destroyUser'])->name('profile.destroy');

and my view :

 <form action="{{ route('profile.destroy', auth()->user()->name) }}" method="POST">
                        @csrf
                        @method('delete')
                        <button type="submit" class="text-white bg-red-600 hover:bg-red-800 focus:ring-4 focus:ring-red-300 font-medium rounded-lg text-sm inline-flex items-center px-3 py-2.5 text-center mr-2 dark:focus:ring-red-900">Delete</button>
                    </form>

My HTML form not work but in code is all fine, actually

Below I have two codes, one in html and one in php. the form when I press the send button does not work and in php the post variable is empty, no variable is sent and I want help to see what the problem is.

HTML FORM:

<form class="form-v" action="./labelconf.php" method="POST" >
                <p class="p-title-form" style="text-align: center; font-size:20px; font-weight:bolder; text-decoration:underline;">Creare eticheta</p>
                <div class="component-form-v">
                    <div class="div-s-row">
                        <label class="label">Cod bare produs</label>
                        <i onclick="WarningBarcode()" class="icon-hint fa-solid fa-circle-question"></i>
                    </div>
                    <input type="text" name="barcode" id="bari" class="input" maxlength="20" pattern="[0-9]+" placeholder="Barcode">
                </div>
                <div class="component-form-v">
                    <div class="div-s-row">
                        <label class="label">Name</label>
                        <i onclick="WarningNameProd()" class="icon-hint fa-solid fa-circle-question"></i>
                    </div>
                    <input type="text" name="name" required class="input" minlength="1" maxlength="25" placeholder="Nume produs">
                </div>
                <div class="component-form-v">
                    <div class="div-s-row">
                        <label class="label">Price</label>
                        <i onclick="WarningPrice()" class="icon-hint fa-solid fa-circle-question"></i>
                    </div>
                    <input type="text" name="pret" required class="input" minlength="1" pattern="[0-9,.]+" placeholder="Price">
                </div>
                <div class="component-form-v">
                    <div class="div-s-row">
                        <label class="label">Contine Garantie?</label>
                    </div>
                    <select name="SGR" id="garantie" class="select">
                        <option value="0">Nu</option>
                        <option value="1">Da</option>
                        <option value="NaN">Nu se stie</option>
                    </select>
                </div>
                <input type="submit" name="submit" class="button btn" value="Creeaza eticheta">
            </form>

PHP Code:

<?php

include_once("./dbch.php");


if (isset($_POST["submit"])) {
    
    //another code to run 

} else {
    // Afisam mesaj pentru debugging
    echo "FORM IS NOT SEND!"; // this error apear all time 
}
?>

PS: Some varables/attributes names is in romanian language and you can google translate for translate words, if exist

I tried and modify code to be code simple but not work all my ideas…

Can’t find php.ini

I was trying to fix my PHP server and upon using the phpinfo(); to check your current php configuration. I have found out that my Configuration File (php.ini) Path has (no value) on it. even though I have a php.ini file. ( I am using Xampp and it is located under C:xamppphp) is there any way to fix this?

PHP detecting no result for PDO query

I am using PHP to fetch and determine the highest ID number for a category, then create the next id in order. The IDs are alphanumeric, a two letter code plus the numerical count ie: TH2, FR23.

Using the PDO code below, I am successfully able to retrieve the highest numbered ID for the category and increment it by one. But if there are no IDs using the letter pair, the process fails because the $hotelID variable is not generated. If the letter pair doesn’t exist in the database yet it should generate the first ID ie: TH1 or FR1.

My SQL:

// find highest existing id code with that two letter code
$newHtlId = $offbase->query("SELECT * FROM hotelMstr WHERE hotelID LIKE '%$cntrycode%' ORDER BY hotelID DESC LIMIT 1");
while ($htlID = $newHtlId->fetch(PDO::FETCH_ASSOC)) {
    if ($newHtlId->rowCount() == 0) {
        $hotelID = $cntrycode.'1';
    }
    else {
        $hotelID = ++$htlID['hotelID'];
    }
}

The $cntrycode is the two letters shown in the id examples.

Revised version based on all the comments below, which does what we want. Thanks all.

// find highest existing id code with that two letter code
$newHtlId = $offbase->query("SELECT * FROM hotelMstr WHERE hotelID LIKE '$cntrycode%' ORDER BY hotelID DESC LIMIT 1");
if($htlID = $newHtlId->fetch(PDO::FETCH_ASSOC)) {
    $hotelID = ++$htlID['hotelID'];
}
else {
    $hotelID = $cntrycode.'1';
}

How to Filter collection based on key?

I have a collection which is like this:

IlluminateSupportCollection {#456 ▼ // appHttpControllersUserController.php:42
  #items: array:4 [▼
    0 => array:10 [▼
      "to" => "12145"
      "from" => "1833"
      "type" => "MMS"
      "smsCount" => 3
      "status" => "PENDING"
      "error" => "No Error"
      "description" => "Message sent, waiting for delivery report"
      "sentAt" => "2024-04-06T05:29:20.791Z"
      "doneAt" => "2024-04-06T05:29:22.779Z"
      "messageId" => "27a13e81"
    ]
    1 => array:10 [▼
      "to" => "1215"
      "from" => "18334"
      "type" => "MMS"
      "smsCount" => 3
      "status" => "DELIVERED"
      "error" => "No Error"
      "description" => "Message delivered to handset"
      "sentAt" => "2024-04-06T05:26:44.683Z"
      "doneAt" => "2024-04-06T05:26:46.423Z"
      "messageId" => "ebb9330c"
    ]
    2 => array:10 [▶]
    3 => array:10 [▶]
  ]
  #escapeWhenCastingToString: false
} 

I want to filter the arrays based on type (type could be MMS & SMS) and month from sendAt. I want to send the data to chart.js. So I want to filter type every months no of MMS & SMS sent.
How can i grouping the collection?
I was trying in following way, But couldn’t get appropriate output?

$selectedElements = new Collection($selectedElements);
$filteredAndGrouped = $selectedElements
          ->where('type', 'MMS')
          ->groupBy(function ($item) {
                    // Extract year and month from the date string
        $dateParts = explode('-', substr($item['sentAt'], 0, 10)); // Extract yyyy-mm from the date string
                   return $dateParts[0] . '-' . $dateParts[1]; // Return yyyy-mm format
 });