Есть ли у них какой-либо способ L oop через данные массива и создать из него другой массив? - PullRequest
0 голосов
/ 05 августа 2020

Я пытаюсь создать массив из этого ввода:

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.
    )
)

для вывода:

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
    )
)

Здесь [y] будет количество раз, когда дата повторяется здесь из ввода .

1 Ответ

1 голос
/ 05 августа 2020

См. Пример ниже

<?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 );

Выход

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

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

)

Протестируйте здесь: http://sandbox.onlinephpfunctions.com/code/c6b7be9876828c41235e01b1e7eb6434f65db5f1

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...