search

Home  >  Q&A  >  body text

Adds a new object to a specific existing array name and saves it using the index value

I know the best way is probably to save the new object at the end of the existing array without a name, but I want to make it a little more complicated to learn how to do this and have it at index value [0] of the array instead A new object is added at the end [arr.length - 1] and I need to save it in a specific array name because in this example I will have multiple arrays. Information is collected by HTML forms.

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';             
    }
}
    
?>

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"
    },
        .
        .
        .
        .
    {      // <- 这是在索引值[arr.length - 1]处添加的最新对象 //
        "year": "2024",
        "link": "xxxxxx_03.html"
    }
]

But what I want to achieve is this:

{
    "newsFeeder": [   // <- 这是我需要添加新对象的数组 //
        {      // <- 这是在索引值[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":[      // 我需要保持此数组不变 //
        {"a":"01.webp", "title":"title 01"},
        {"a":"02.webp", "title":"title 02"},
        {"a":"03.webp", "title":"title 03"}
    ]
}

I've tried different methods, but those either clear everything and only add the collected information, or end up breaking things. Hope this helps me learn how to achieve this goal!

P粉006847750P粉006847750224 days ago408

reply all(2)I'll reply

  • P粉466909449

    P粉4669094492024-04-04 18:47:26

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

    Similar to the following code:

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

    reply
    0
  • P粉743288436

    P粉7432884362024-04-04 14:10:24

    You can use array_unshift to achieve this function. It shifts all array elements backward one and inserts the second parameter at index 0 of the first parameter of the function call.

    array_unshift($array_data, $extra);

    reply
    0
  • Cancelreply