簡體   English   中英

PHP - strpos對我不起作用?

[英]PHP - strpos doesn't work correctly for me?

所以我試圖通過使用strpos搜索JSON,但它不適合我。 我總是得到“物品不存在”。

這是PHP

$getItems = file_get_contents('Items.json');
$decodeItems = json_decode($getItems,true);

//$output = ''.$decodeItems['items'][0]['name'].'';
$output = '';

if(isset($_POST['search'])){
    $searchq = $_POST['search'];
    $searchq = preg_replace("#[^0-9a-z]#i","",$searchq);

    foreach($decodeItems['items'] as $data){
        if($chance = strpos($data, $searchq) !== FALSE){
            if($data['name'] == $chance){
                $name = $data['name'];
                $output .= "<div>".$name."</div>";
            }
        }
        else{
            $output = 'Items no';
        }
    }
}

這是示例JSON

{"img":"-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQh5hlcX0nvUOGsx8DdQBJjIAVHubSaIAlp1fb3YihQ-tWglYy0lfjjOr6fxjpQ7MFz373Fodyl0AXh-ENkMWinJ4eXcA8-ZFHUq1K_xum70ZO56oOJlyUgjHI5fA","name":"&#x2605 Bowie Knife","assetid":"6442574944","myprice":"155.36","condition":"","originalname":"\u2605 Bowie Knife","inspect":"steam:\/\/rungame\/730\/76561202255233023\/+csgo_econ_action_preview%20S76561198034643020A6442574944D2305887113904442996","special":"0","floatvalue":null,"bitskinsprice":"117.36"}

從手冊中strpos的返回值:

返回針存在於相對於haystack字符串開頭的位置(與offset無關)。 另請注意,字符串位置從0開始,而不是1。

如果未找到針,則返回FALSE。

所以,我建議你改變代碼的這一部分:

if(strpos($data['name'], $searchq) === true)

if(strpos($data['name'], $searchq) !== FALSE)

根據以下評論更新我的答案。

JSON需要遵循以下表示法才能使上述代碼工作:

{"items":[
   {
      "img":"img1",
      "name":"name1",
      "assetid":"1",
      "myprice":"155.36",
      "condition":"",
      "originalname":"name1 original",
      "inspect":"whatever",
      "special":"0",
      "floatvalue":null,
      "bitskinsprice":"117.36"
   },
   {
      "img":"img2",
      "name":"name2",
      "assetid":"2",
      "myprice":"175.11",
      "condition":"",
      "originalname":"name2 original",
      "inspect":"whatever2",
      "special":"0",
      "floatvalue":null,
      "bitskinsprice":"55.55"
   }
]};

根據以下評論更新我的答案。

好的,我對您的腳本進行了一些更改,以正確處理JSON文件。

$getItems = file_get_contents('Items.json');
$decodeItems = json_decode($getItems,true);

//$output = ''.$decodeItems['items'][0]['name'].'';
$output = '';

if(isset($_POST['search'])){
    $searchq = $_POST['search'];
    $searchq = preg_replace("#[^0-9a-z]#i","",$searchq);

    foreach($decodeItems['items'] as $data){
       // this was *if($chance = strpos($data, $searchq) !== FALSE){*
       if(strpos($data['name'], $searchq) !== FALSE) {
          // here was another unneeded *if($data['name'] == $chance){*
          $name = $data['name'];
          $output .= "<div>".$name."</div>";
       }
    }

    if (empty($output)) {
      $output = 'Items no';
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM