使用PHP在JSON文件中搜索包含德语字符的字符串

时间:2018-10-10 01:00:39

标签: php

JSON文件:

{"verbs":[{"_id":1,"option1":"ändern","option2":"öl","option3":"über","answer":"über"},{"_id":2,"option1":"mit","option2":"aus ","option3":"zu","answer":"aus "}]}

代码:

<?php

  $string = file_get_contents("http://xyz-abc.com/xyz.json");
  $arrays = json_decode($string,true);

   $found = array_search( "ändern", array_column( $arrays, 'option1' ) );
if( $found === False ) echo "Not Found";

else   echo $data[$found]['option1'];

我正在JSON文件中搜索“ändern”。我得到的输出:未找到。谁能在我的代码中找到错误?

1 个答案:

答案 0 :(得分:1)

这有效:

<?php
$string = '{"verbs":[{"_id":1,"option1":"ändern","option2":"öl","option3":"über","answer":"über"},{"_id":2,"option1":"mit","option2":"aus ","option3":"zu","answer":"aus "}]}';
$arrays = json_decode($string,true);

foreach ($arrays as $array) {
    $needle = "ändern";
    $found = array_search($needle, array_column($array, 'option1'));

    if($found === false) {
        echo 'Not Found: ' . $needle; 
    } else {
        echo 'Found: ' . $needle;
    }
}

您找不到任何内容,因为您没有将$arrays视为多维数组,$arrays的查找方式如下:

array(1) {
    'verbs' =>
    array(2) {
    [0] =>
    array(5) {
        '_id' =>
        int(1)
        'option1' =>
        string(7) "ändern"
        'option2' =>
        string(3) "öl"
        'option3' =>
        string(5) "über"
        'answer' =>
        string(5) "über"
    }
    [1] =>
    array(5) {
        '_id' =>
        int(2)
        'option1' =>
        string(3) "mit"
        'option2' =>
        string(4) "aus "
        'option3' =>
        string(2) "zu"
        'answer' =>
        string(4) "aus "
    }
    }
}