Skip to content
Advertisement

array_search function for JSON File in PHP

File:

[
{
    "Zustand":"geschlossen",
    "Losnummer":1,
    "Gewinnklasse":"A",
    "Preis":10
},

{
    "Zustand":"geschlossen",
    "Losnummer":2,
    "Gewinnklasse":"B",
    "Preis":20
},

{
    "Zustand":"geschlossen",
    "Losnummer":3,
    "Gewinnklasse":"B",
    "Preis":30
} 
]

I want an array of it so i do:

<?php

$str = file_get_contents("lose.json");
$json = json_decode($str, true);

 ?>

And then i want to enter a value and this value should identify the entry from the Array and delete the whole entry:

<?php
    if (($key = array_search(10, $json)) !== false) {
       unset($json[$key]);
        echo"test";
    }
?>

I entered the value: 10 so the first entry of the array should be deleted.

I think array_search cant read my $json but i dont know why. Can smb fix this ?

Advertisement

Answer

You also need to specify the key you are searching (‘Preis’). array_column() will help us:

$array = json_decode($json, true);

$key = 'Preis';
$value = 10;
$index = array_search( $value, array_column($array, $key) );
if( is_numeric($index) ){
    unset($array[$index]);
}

print_r($array);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement