0

I have a json file with this content :

[
    {
    "id": "apple",
    "symbol": "app",
    "name": "Apple",
    },
]

I Want To Search In This Json File In id Or symbol Or name Columns, I Write This Code :

    $nameOrIDOrSymbol="apple"; // user types id or symbol or name.
    $names= json_decode(file_get_contents("file.json", true), true);
    $name_key1 = array_search($nameOrIDOrSymbol,array_column($names, 'id')
    $name_key2 = array_search($nameOrIDOrSymbol,array_column($names, 'name');
    $name_key3 = array_search($nameOrIDOrSymbol,array_column($names, 'symbol');
if($name_key1){
    var_dump($name_key1);
}elseif($name_key2){
    var_dump($name_key2);
}elseif($name_key3){
    var_dump($name_key3);
}

How Can I Search In This Three 3 Array Columns Only Once With array_search Or Another Function? For example search like this :

$name_key = array_search($nameOrIDOrSymbol,array_column($names, 'id','name','symbol')
2
  • What exactly do you want to get? An object that contains a key with value ex. apple? Or just index in array that contains that object? Commented Sep 5, 2021 at 8:31
  • another person answered , thanks Commented Sep 5, 2021 at 9:36

1 Answer 1

1

Currently you search first in the 'id' column, then in the 'name' column, and finally in the 'symbol' column. If, at any stage, you encounter a match you return the array key. If you want to keep this functionality you have to look through the columns in that order.

You could combine the three columns into one array, juggle a bit with the keys, and do a single search that way, but I don't think that's very efficient.

Why not restructure you code a bit? For instance like this:

$query   = 'apple';
$columns = ['id', 'name', 'symbol'];
$data    = json_decode(file_get_contents('file.json', true), true);
foreach ($columns as $column) {
    $key = array_search($query, array_column($data, $column);
    if ($key !== false) break;
}
var_dump($key);

Now you've only used array_search() once, in a way.

This code is more efficient than yours because it stops searching as soon as it has found 'apple' in a column. Your code always searches through all columns.

Note that I actually check that array_search() returns false, unlike what you did, which would not have responded when this functions returned key zero.

Also note that, if ever the need arises, you can now easily add more columns without having to add more repeating lines of code.

Sign up to request clarification or add additional context in comments.

Comments

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.