doujing5937 2013-04-12 18:54
浏览 28
已采纳

在数组的前三个元素中包含一个值

I am using the following code to get an array of some values.

<?php

$sms = array();
foreach($contact_number as $value) {    

    $sms[] = array($value, $message);       

}   

 var_dump($sms);    

What I am trying to do now is include a variable $abc = "From Charlie Sheen"; with $message in the first 3 elements of the above array, so that when the first three message appears I can see "From Charlie Sheen" at the end of the original message.

Could you please tell me how to solve this problem (its better if I don't have to make any change in the above array; I wish to add a new line of code to solve this problem)

The output of var_dump($sms); is :

array(2) {
    [0]=> array(2) {
        [0]=> string(3) "123"
        [1]=> string(15) "This is Message"
    }
    [1]=> array(2) {
        [0]=> string(3) "456"
        [1]=> string(15) "This is Message"
    }
}   
  • 写回答

3条回答 默认 最新

  • duan1933 2013-04-12 19:07
    关注
    $sms = array();
    $toAdd = 3;
    foreach($contact_number as $value) {
        if($toAdd > 0) {
            $sms[] = array($value, $message . 'charlie bla bla');       
           --$toAdd;
        } else {
            $sms[] = array($value, $message);
        }
    }
    

    Or shorter :

    $sms = array();
    for($toAdd = 3, $i = 0, $l = count($contact_number); $i < $l; --$toAdd, ++$i)
        $sms[] = array($value, $toAdd > 0 ? $message . 'charlie bla bla' : $message);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案