dongping8572
dongping8572
2019-05-09 17:02

两个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 dongrang2186 2年前

    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

    点赞 评论 复制链接分享

为你推荐