programing

json_encode()를 사용할 때 어레이 인덱스 참조를 제거하는 중

nicegoodjob 2023. 2. 11. 23:25
반응형

json_encode()를 사용할 때 어레이 인덱스 참조를 제거하는 중

jQuery's로 작은 어플리케이션을 만들었습니다.datepicker사용할 수 없는 날짜를 다음과 같은 JSON 파일에서 설정합니다.

{ "dates": ["2013-12-11", "2013-12-10", "2013-12-07", "2013-12-04"] }

지정된 날짜가 이미 이 목록에 있는지 확인하고 만약 있다면 삭제하고 싶습니다.현재 코드는 다음과 같습니다.

if (isset($_GET['date'])) //the date given
{
    if ($_GET['roomType'] == 2)
    {
        $myFile = "bookedDates2.json";
        $date = $_GET['date'];
        if (file_exists($myFile))
        {
            $arr = json_decode(file_get_contents($myFile), true);
            if (!in_array($date, $arr['dates']))
            {
                $arr['dates'][] = $_GET['date']; //adds the date into the file if it is not there already
            }
            else
            {
                foreach ($arr['dates'] as $key => $value)
                {
                    if (in_array($date, $arr['dates']))
                    {
                        unset($arr['dates'][$key]);
                        array_values($arr['dates']);
                    }
                }
            }
        }

        $arr = json_encode($arr);
        file_put_contents($myFile, $arr);
    }
}

여기서의 문제는 어레이를 다시 인코딩하면 다음과 같이 보인다는 것입니다.

{ "dates": ["1":"2013-12-11", "2":"2013-12-10", "3":"2013-12-07", "4":"2013-12-04"] }

인코딩 후에 키가 표시되지 않고 JSON 파일에서 일치하는 날짜를 찾아 삭제할 수 있는 방법이 있습니까?

문제에 사용:

$arr['dates'] = array_values($arr['dates']);
//..
$arr = json_encode($arr);

왜요? 배열의 순서를 다시 정하지 않고 키를 설정 해제하기 때문입니다.그 후 JSON에서 이 키를 유지하는 유일한 방법은 인코딩 키입니다.신청 후array_values()단, 주문된 키가 제공됩니다(다음부터 시작:0키를 포함하지 않고 올바르게 부호화할 수 있습니다.

반환값을 무시하고 있습니다.array_values어레이를 재인덱스화하려고 할 때 사용합니다.정답은

$arr['dates'] = array_values($arr['dates']);

재인덱스화도 외부로 이동해야 합니다.foreach루프, 여러 번 인덱스를 재인덱스해도 의미가 없습니다.

Laravel 컬렉션에서는 (혹시) 할 수 있습니다.

    $newArray = $collection->values()->toArray();

또는

    $jsonEncoded = $collection->values()->toJson();

두 번째 매개 변수를 '로 전달하십시오.JSON_PRETTY_PRINTjson_encode()기능:

json_encode($arr, JSON_PRETTY_PRINT);

또는

json_encode($arr, 128);

언급URL : https://stackoverflow.com/questions/20372982/removing-array-index-reference-when-using-json-encode

반응형