M
M
MrZed2021-07-01 23:11:48
PHP
MrZed, 2021-07-01 23:11:48

PHP Array to List?

Hey! There is a .json file:

file.json
{
    "posts": [
        {
            "id": 0,
            "title": "Авто 1",
            "description": "Описание",
            "active": true
        },
        {
            "id": 1,
            "title": "Авто 2",
            "description": "Описание",
            "active": true
        },
        
        {
            "id": 2,
            "title": "Авто 3",
            "description": "Описание",
            "active": true
        }
    ]
}
After executing this code:
file.php
$json = file_get_contents('file.json');
$json_read = json_decode($json, true);

unset($json_read['posts'][1]);

$json_reads = json_encode($json_read, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
echo ($json_reads);
As a result, I get json in the following format:
{
    "posts": {
        "0": {
            "id": 0,
            "title": "Авто 1",
            "description": "Описание",
            "active": true
        },
        "2": {
            "id": 2,
            "title": "Авто 3",
            "description": "Описание ",
            "active": true
        }
    }
}
How do I get json in this format:
{
    "posts": [
        {
            "id": 0,
            "title": "Авто 1",
            "description": "Описание",
            "active": true
        },
        {
            "id": 2,
            "title": "Авто 3",
            "description": "Описание - 1",
            "active": true
        }
    ]
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2021-07-02
@MrZed

$json_read['posts'] = array_values($json_read['posts']);

$json_reads = json_encode($json_read, ...)

B
Bogdan Khvalko, 2021-07-01
@quitting

What's stopping you

//получаем данные)
$data = json_decode($jsondata);   
$data->posts = (array)$data->posts;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question