简体   繁体   中英

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM