0

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

<?php

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

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

}   

 var_dump($sms);    

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

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

的输出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"
    }
}   
4

3 回答 3

1
$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);
于 2013-04-12T19:07:13.440 回答
0

您可以在创建数组时通过添加计数器来执行此操作

<?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);    
于 2013-04-12T19:07:18.790 回答
0

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

<?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';
        }

    }

?>
于 2013-04-12T19:28:25.033 回答