0

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 ?

1
  • "I think array_search cant read my $json" - that's not it, you are simply searching for something the array does not contain. array_search compares against the elements on the top level, which are themselves arrays here. Trying to compare an array with 10 of course does not result in true. Commented Nov 18, 2021 at 11:36

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

hi mate, yes that what exactly im looking for. It works! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.