我有一个定义为$ array [colname]的数组。对于$ array [colname]中的每个值,我想在最后添加一段文本。里面的值是字符串,我也会附加一个字符串。
答案 0 :(得分:4)
至少有两种可能性
编辑阵列:
foreach($a as &$v) {
$v .= 'APPENDED';
}
或
foreach($a as $k => $v) {
$a[$k] = $v . 'APPENDED';
}
按mapping创建一个新数组,将旧值设为新值:
$appended_array = array_map(function($v) { return $v . 'APPENDED'; }, $a);
答案 1 :(得分:1)
喜欢这个?您可以轻松地迭代通过数组
以下是文档:http://php.net/manual/en/control-structures.foreach.php
提示:下次您应该在google和php.net上进行搜索,因为大多数默认内容都已记录在案,并且在您的问题中,您使用了自己需要的正确关键字
<?php
//Could write this shorter
$array = array();
$array['column1'] = 'value1';
$array['column2'] = 'value2';
//This is the short way
//http://php.net/manual/en/language.types.array.php
$array = array('column1' => 'value1', 'column2' => 'value2');
//Iterate throug every value in $array (That is every $array[colname])
//The & charachter before the $value means pass-by-reference you should do some research to understand this ;)
//foreach($array['colname'] as &$value) { for a single column with multiple values in it
foreach($array as &$value) {
// .= is the same as $value = $value . 'append'
// This way we append the text
$value .= 'append';
}
//Outputs all values in $array
print_r($array());
?>
答案 2 :(得分:0)
您可以使用如下所示的array_walk:
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
function test_alter(&$item1, $key, $string)
{
$item1 = "$item1 : $string";
}
array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";
array_walk($fruits, 'test_print');
?>
输出将如下:
... and after:
d. lemon:fruit
a. orange:fruit
b. banana:fruit
c. apple:fruit
答案 3 :(得分:0)
此处提供的测试解决方案数组与您的结构匹配
<?php
$array = array();
$array['c1'] = array(1=>'data1', 2=>'data2', 3=>'data3', 4=>'data4');
$array['c2'] = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
echo '<pre> Original Array : <br/>';
print_r($array);
foreach($array as $key=>$value)
{
foreach($value as $sub_key=>$sub_value)
{
$textToAppend = '_AppendedMe';
echo '<br/> brfore : '.$value[$sub_key];
$sub_value .= $textToAppend;
$array[$key][$sub_key]=$sub_value;
echo '<br/> after : '.$value[$sub_key];
}
}
echo '<br/> Array after : ';
print_r($array);
echo '</pre>';
?>