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

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

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝