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

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

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装