json 如何在foreach和if else if条件中仅显示一次回显

hc8w905p  于 2022-12-01  发布在  其他
关注(0)|答案(1)|浏览(112)

下面是我json数据
{“订单编号”:“#BCB28FB2”,“称呼”:“先生”,“姓名”:“测试数据”,“购物车”:[ {“编号”:13,“姓名”:“测试1”,“治疗类型”:“测试”,},{“编号”:14,“姓名”:“测试2”,“治疗类型”:“测试”,},{“编号”:15,“姓名”:“方案组”,“治疗类型”:“方案组”,},{“编号”:16,“姓名”:“方案包”,“治疗类型”:“方案包”,},] }
这是我的密码

foreach($data['cart'] as $value){
   if($value['treatment_type'] == 'tes'){
      echo "Its a tes<br>";
   }
   elseif($value['treatment_type'] == 'panel'){
      echo "Its a panel<br>";
   }else{
      echo "Its a paket<br>";
   }
}

我的网站显示
enter image description here
enter image description here如何这样展示

atmip9wb

atmip9wb1#

您可以使用array_unique来完成此工作

  • 将所有$value ['treatment_type']放入临时数组
  • 对其应用array_unique

代码是

<?php

$json='{ "order_id":"#BCB28FB2", "salutation":"Mr", "name":"Testing Data", "cart":[ { "id":13, "name":"tes1", "treatment_type":"tes" }, { "id":14, "name":"tes2", "treatment_type":"tes" }, { "id":15, "name":"Panel", "treatment_type":"panel" }, { "id":16, "name":"Paket", "treatment_type":"paket" } ] }';

$data=json_decode($json, true);

foreach($data['cart'] as $value){
   $data2[]=$value['treatment_type'];
}

$data3=array_unique($data2);

foreach($data3 as $value){

   if($value == 'tes'){
      echo "Its a tes<br>";
   }
   elseif($value == 'panel'){
      echo "Its a panel<br>";
   }else{
      echo "Its a paket<br>";
   }
}
?>

实际上,对于foreach循环,您可以进一步简化为以下内容:

foreach($data3 as $value){
  echo "Its a " . $value . "<br>";
}

您可以在以下Sandbox URL查看执行结果:
https://onlinephp.io/c/f503c

相关问题