Home > Net >  JSON - Saving new Object inside specific existing Array name | also adding it at Index Value [0] ins
JSON - Saving new Object inside specific existing Array name | also adding it at Index Value [0] ins

Time:09-17

I know that probably is better to save new objects at the end of an existing array with no name, but I would like to complicate things a little to learn how to do it, and add new object at the index value [0] instead of the end [arr.length - 1] of an array, also I need to save it inside an specific array name because I will have more than one in this sample. The information is collected by an html form.

What I have is:

<?php
    
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                
    function get_data() {
        $file_name='newsFeeder'. '.json';

        if(file_exists("./feeder/{$file_name}")) {
            $current_data=file_get_contents("./feeder/{$file_name}");
            $array_data=json_decode($current_data, true);

            $extra=array(
                'year' => $_POST['year'],
                'link' => $_POST['link'],
                'img' => $_POST['img'],
            );

            $array_data[]=$extra;
            echo "file exist<br/>";
            return json_encode($array_data, JSON_PRETTY_PRINT);
        }
        else {
            $datae=array();
            $datae[]=array(
                'year' => $_POST['year'],
                'link' => $_POST['link'],
                'img' => $_POST['img'],
            );
            echo "file not exist<br/>";
            return json_encode($datae, JSON_PRETTY_PRINT);
        }
    }

    $file_name='newsFeeder'. '.json';
    
    if(file_put_contents("./feeder/{$file_name}", get_data())) {
        echo 'success';
    }               
    else {
        echo 'There is some error';             
    }
}
    
?>

and the result is a JSON file like this:

[
    {
        "year": "2022",
        "link": "xxxxxx_01.html",
        "img": "xxxxxx_01.webp"
    },
    {
        "year": "2023",
        "link": "xxxxxx_02.html",
        "img": "xxxxxx_02.webp"
    },
        .
        .
        .
        .
    {      // <- This is the newest object added at index value [arr.length - 1] //
        "year": "2024",
        "link": "xxxxxx_03.html"
    }
]

But what I want to achieve is this:

{
    "newsFeeder": [   // <- this is the array where I need to add new objects to //
        {      // <- This is the newest object added at index value [0] //
            "year": "2024",
            "link": "xxxxxx_06.html",
            "img": "xxxxxx_06.webp"
        },
        .
        .
        .
        .
        {
            "year": "2023",
            "link": "xxxxxx_02.html",
            "img": "xxxxxx_02.webp"
        },
        {
            "year": "2022",
            "link": "xxxxxx_01.html",
            "img": "xxxxxx_01.webp"
        }
    ],

    "whyComplicate_things":[      // I need to let this array untouched //
        {"a":"01.webp", "title":"title 01"},
        {"a":"02.webp", "title":"title 02"},
        {"a":"03.webp", "title":"title 03"}
    ]
}

I tried different approach but those only erase everything and add only the one with the info collected, or ending breaking things up. Help to learn how to achieve this is appreciated!

CodePudding user response:

To add to the beginning of the array, you can append with , ...$array_name if using PHP > 7.4

Something like this:

$array_name = [array(
    'year' => $_POST['year'],
    'link' => $_POST['link'],
    'img' => $_POST['img']
), ...$array_name];

CodePudding user response:

You can achieve this with array_unshift. It moves all array elements 1, and inserts the second parameter of the function call on index 0.

array_unshift($array_data, $extra);
  • Related