简体   繁体   English

PHP从foreach键获取特定值

[英]PHP get a specific value from a foreach key

I am trying to extract a value from a foreach loop: 我试图从foreach循环中提取一个值:

$telephone1 = '1231315';
$telephone2 = '42342342';

$telephoneNums = array($telephone1,$telephone2);

foreach($telephoneNums as $telephoneNum){
    $telephoneNum = 't'.$telephoneNum;
}

echo $telephoneNum[0];

the value that is being output is t 输出的值是t

If I do echo $telephoneNum[1]; 如果我echo $telephoneNum[1]; I get 4 我得到4

I'd like to get t1231315 for echo $telephoneNum[0] 我想为echo $telephoneNum[0]获得t1231315

This is simple problem but I am not sure what I am doing wrong. 这是一个简单的问题,但是我不确定自己在做什么错。

The problem is you're just assigning a string and not pushing an array to assign: 问题是您只是分配一个字符串而没有推送数组来分配:

$telephoneNum = 't'.$telephoneNum;

Use the array assignment: 使用数组分配:

$telephoneNum = array();
foreach($telephoneNums as $tel){
    $telephoneNum[] = 't'.$tel;
               // ^ this is important
}
echo $telephoneNum[0];

Sidenote: 边注:

In case you're wondering how echo $telephoneNum[0]; 如果您想知道如何echo $telephoneNum[0]; is t and echo $telephoneNum[1]; techo $telephoneNum[1]; 4. Is because since the last iteration is the value t42342342 overwriting $telephoneNum (the string) . 4.是因为自从上次迭代以来,值t42342342覆盖了$telephoneNum (字符串)。 And this is a behaviour of string access in PHP. 这是PHP中的字符串访问行为。

http://php.net/manual/en/language.types.string.php http://php.net/manual/en/language.types.string.php

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. 可以通过使用方括号将字符串后的字符从零开始偏移来访问和修改字符串中的字符,如$ str [42]。 Think of a string as an array of characters for this purpose. 为此,可以将字符串视为字符数组。

Try this.. 尝试这个..

<?php
$telephone1 = '1231315';
$telephone2 = '42342342';

$telephoneNums = array($telephone1,$telephone2);
$telephoneNum=array();
foreach($telephoneNums as $tele){
   $telephoneNum[] = 't'.$tele;
}
echo $telephoneNum[0];//t1231315
echo $telephoneNum[1];//t42342342
?>

This is how you will need to do. 这就是您需要做的。 There you are extracting the first character from a string which otherwise you should have extracted from an array: 在那里,您将从字符串中提取第一个字符,否则应从数组中提取:

$telephone1 = '1231315';
$telephone2 = '42342342';

$telephoneNums = array($telephone1,$telephone2);
$i = 0;
foreach($telephoneNums as $telephoneNum){
  $telephoneNums[$i] = 't'.$telephoneNum;
   $i++;
}

echo $telephoneNums[0]."\n";
echo $telephoneNums[1];

use this code 使用此代码

$telephone1 = '1231315';
$telephone2 = '42342342';

$telephoneNums = array($telephone1,$telephone2);
 $telephoneNumbers=array();
foreach($telephoneNums as $telephoneNum){
    $telephoneNumbers[] = 't'.$telephoneNum;//telephoneNumbers[] is an array
}

echo $telephoneNumbers[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM