dongping8572 2019-05-09 17:02
浏览 204
已采纳

两个JSON数据合并和ECHO与PHP

What is the difference from the previous questions?

In other questions, the numbers of both JSON data were equal. This question does not equal JSON files.

I have two JSON data. One of them contains only 2 values. The other one contains six values. I'm trying to distinguish with IF ELSE, but two of each value is written. In line with the numbers in the first JSON, I want to separate the second JSON data.

For example:

3 -> val3
5->  val5

First JSON:

{"0":"3","1":"5"}

Second JSON:

{"val1":"ValueOne","val2":"ValueSecond","val3":"ValueThree","val4":"4","val5":"ValueFive","val6":"ValueSix"}

$first = json_decode($jsonFile1);
$second = json_decode($jsonFile2);

foreach ($first as $key => $firstvalue) {
  foreach ($second as $secondvalue) {
    if (substr($firstvalue, -1) == $secondvalue) {  <-- 'valX' => 1
       echo "<strong>". $firstvalue . "</strong><br>";
    } else { 
       echo "<em>". $firstvalue . "</em>";
    } 
  }
}

Result:


  • ValueOne
  • ValueOne
  • ValueSecond
  • ValueSecond
  • ValueThree
  • ValueThree
  • ValueFour
  • ValueFour
  • ValueFive
  • ValueFive
  • ValueSix
  • ValueSix

What could be the reason?

  • 写回答

1条回答 默认 最新

  • dongrang2186 2019-05-09 17:16
    关注

    Not sure how you get the output you say you are, but the repeat is due to looping each item for every item in the second array - hence each option is in there twice.

    This version uses in_array() to see if the last character of the key is in the second JSON list (note that this is converted to an array and not objects using true as the second parameter of json_decode())...

    $jsonFile1 = '{"val1":"ValueOne","val2":"ValueSecond","val3":"ValueThree","val4":"4","val5":"ValueFive","val6":"ValueSix"}';
    $jsonFile2 = '{"0":"3","1":"5"}';
    $first = json_decode($jsonFile1);
    $second = json_decode($jsonFile2, true);
    
    foreach ($first as $key => $firstvalue) {
        if (in_array(substr($key, -1),$second)) {
            echo "<strong>". $firstvalue . "</strong><br>";
        } else {
            echo "<em>". $firstvalue . "</em><br>";
        }
    }
    

    gives...

    ValueOne
    ValueSecond
    ValueThree
    4
    ValueFive
    ValueSix

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?