عندما استعمل دالة unset يتغير شكل بيانات json

السلام عليكم

لدي مشكلة مع دالة unset استخدمها لازالة عنصر من ملف json ، المشكلة هي عندما استخدم الدالة بهذا الشكل

$file_data = json_decode(file_get_contents($file), true);
$key = array_search($_POST['id'], array_column($file_data, 'id'));
unset($file_data[$key]);
file_put_contents($file, json_encode($file_data));

يتم تغيير شكل الداتا

من

[{"id": 1671308031,
"rss_link": "aa",
"website_name": "aa",
"website_icon": "aa",
"website_category": "Female"
},
{"id": 1671308037,
"rss_link": "bb",
"website_name": "bb",
"website_icon": "bb",
"website_category": "Male"
},
{"id": 1671308046,
"rss_link": "cc",
"website_name": "cc",
"website_icon": "cc",
"website_category": "Male"
}
]

الى

{"0": {"id": 1671308031,
"rss_link": "aa",
"website_name": "aa",
"website_icon": "aa",
"website_category": "Female"
},
"2": {"id": 1671308046,
"rss_link": "cc",
"website_name": "cc",
"website_icon": "cc",
"website_category": "Male"
}
}

هل من حل لهذه المشكلة


مرحبا صديقي أنا لست بمبرمج PHP لكن قمت فقط بسؤال ChatGpt عن مشكلتك فقام بكتابة الحل :

$file_data = json_decode(file_get_contents($file), true);
$key = array_search($_POST['id'], array_column($file_data, 'id'));
unset($file_data[$key]);
$file_data = array_values($file_data); // reset the indexes of the array
file_put_contents($file, json_encode($file_data));

The problem is with the way you are encoding the data with json_encode() after removing an element from the array. json_encode() converts a PHP value (typically an array or object) into a JSON string.

By default, json_encode() will encode an indexed array (e.g. [1, 2, 3]) as an array in JSON. However, if you pass an associative array (e.g. ['a' => 1, 'b' => 2, 'c' => 3]) to json_encode(), it will encode it as an object.

In your code, you are using unset() to remove an element from the array, which leaves a gap in the indexes of the array. For example, if you remove the element at index 1, you will have an array with the indexes 0 and 2, but no index 1. This causes json_encode() to treat the array as an associative array and encode it as an object.

To fix this, you can use the array_values() function to reset the indexes of the array after you remove an element. This will ensure that the resulting array is an indexed array and is encoded as an array in JSON.

إن لم تفهم شيء( لا تجيد الإنجليزية ) يمكنني الشرح لك لقد قمت بفهم أين الخلل الخاص بكودك