dongwuchu0314 2016-04-28 04:01
浏览 36
已采纳

PHP在循环中随机打印文本

I have data selected from database in object format. I want to loop it but I also include text randomly to the display. How to add that text to a random place in object? or how to print it randomly once inside the loop?

//Object data

$obj = (object) [

'0' => ['name' => 'Banana'],

'1' => ['name' => 'Potato'],

'2' => ['name' => 'Mango']

];

//addition text will be displayed

$text = 'My random text';

foreach($obj as $d) {

 echo $d->name; 

}

Result can be

  • Banana

  • Potato

  • My random text

  • Mango

Or

  • My random text

  • Banana

  • Potato

  • Mango

Or

  • Banana

  • My random text

  • Potato

  • Mango

...

  • 写回答

4条回答 默认 最新

  • doumeng1897 2016-04-28 04:35
    关注

    Just find the a random position index from your object data like this.

    $randPos = rand(0, count($obj)-1);
    

    And put your random text right after this random index of object data while accessing it through look.

    //addition text will be displayed
    
    $text = 'My random text';
    
    foreach($obj as $k => $d) {
       echo $d->name; 
       if($k == $randPos) echo $text;
    }
    

    Hope this will help to solve your query !!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile