Skip to content
Advertisement

Is their any way to Loop through data of array & create another array from it?

I am trying to create a array from this input:

Array (
    [0] => stdClass Object (
        [id] => 85
        [time] => 2020-07-18 13:34:59
        [user] => 32
        [status] => read
        [type] => profile_view
        [content] => One has viewed your profile. 
    )
    [1] => stdClass Object (
        [id] => 79
        [time] => 2020-07-20 12:16:03
        [user] => 32
        [status] => read
        [type] => profile_view
        [content] => test buyer has viewed your profile.
    )
    [2] => stdClass Object (
        [id] => 76
        [time] => 2020-07-20 12:59:11
        [user] => 32
        [status] => read
        [type] => profile_view_guest
        [url] => 
        [content] => A guest has viewed your profile.
    )
)

to output:

Array (
    [0] => Array (
        [label] => July 18 2020
        [y] => 1
    )
    [1] => Array (
        [label] => July 20 2020
        [y] => 1
    )
    [2] => Array (
        [label] => July 20 2020
        [y] => 1
    )
)

Here [y] will number of times the date repeats here from the input.

Advertisement

Answer

Please see the below example

<?php

// This is your input array
$input = [ ... ];

$output = [];

foreach ( $input as $data ) {
    
    $date = DateTime::createFromFormat( 'Y-m-d H:i:s', $data->time );
    $formatted = $date->format( 'F j Y' );

    // Create empty count
    if ( !array_key_exists( $formatted, $output ) ) {
        $output[ $formatted ] = [
            'label' => $formatted,
            'y' => 0
        ];
    }

    // Increase count
    $output[ $formatted ][ 'y' ]++;

}

// Remove keys
$output = array_values( $output );

print_r( $output );

Output

Array
(
    [0] => Array
        (
            [label] => July 18 2020
            [y] => 1
        )

    [1] => Array
        (
            [label] => July 20 2020
            [y] => 2
        )

)

Test here: http://sandbox.onlinephpfunctions.com/code/c6b7be9876828c41235e01b1e7eb6434f65db5f1

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement