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


Including a value in the first three elements of an array

我使用下面的代码来获取一些值的数组。

<?php
$sms = array();
foreach($contact_number as $value) {    
    $sms[] = array($value, $message);       
}   
 var_dump($sms);    

我现在要做的是在上面数组的前3个元素中包含一个变量$abc = "From Charlie Sheen";$message,这样当前三个消息出现时,我可以在原始消息的末尾看到"来自查理辛"。

你能告诉我如何解决这个问题吗(如果我不需要对上面的数组做任何改变就更好了;我希望添加一行新代码来解决这个问题)

var_dump($sms);的输出为:

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"
    }
}   
$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);
    }
}

或更短:

$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);

可以在创建数组时添加计数器

<?php
  $sms = array();
  $counter = 0;
  foreach($contact_number as $value) {    
     if($counter < 3) { $message .= " From Charlie Sheen"; }
     $sms[] = array($value, $message);       
     $counter++;
  }   
  var_dump($sms);    

从这个例子中很难看出你在做什么…记住,其他联系电话不一定是唯一的,但手机号码"应该"是唯一的。如果您正在制作各种日志系统:

<?php
    $cell_numbers = array(
    '000-555-1212'=>'Charlie Sheen',
    '800-333-4475'=>'Mary Poppins'
    );
    $sms = array();
    //Number from the person texting
    $inbound = $_POST['number'];
    //Message from the person texting
    $message = $_POST['message'];
    if(!empty($cell_numbers[$inbound])){
        $sms[][$number]=$message;   
    }
    foreach($sms as $key=>$tempArr){
       foreach($sms[$key] as $tNum=>$tMes){
           echo "Message from ".$cell_numbers[$tNum]." - $tMes'n";
       }
    }
?>

如果你正在制作一个战争文本电子邮件应用程序,那么你可以这样做:

<?php
    $contacts = array(
    0=>array(
    'number'=>'000-555-1212',
    'name'=>'Charlie Sheen',
    'carrier'=>'Sprint'),
    1=>array(
    'number'=>'800-333-4475',
    'name'=>'Mary Poppins',
    'carrier'=>'ATT'),
    );
    $carriers = array(
    'ATT'=>'txt.att.net',
    'Sprint'=>'messaging.sprintpcs.com',
    'T-Mobile'=>'tomomail.net',
    'Virgin'=>'vmobl.com',
    'Verizon'=>'vtext.com',
    );
    $message = 'Do I know you?';
    $sms = array();
    foreach ($contacts as $key=>$tempArr){
        $to = $contacts[$key]['number'].'@'.$carriers[$contacts[$key]['carrier']];
        if(mail("$to","SMS","$message",$headers = 'From: Tom Hanks <911@vtext.com>' . "'r'n")){
        $SMS[$to] = 'yes';  
        } else {
        $SMS[$to] = 'failed';
        }
    }
?>