这是我处理的多维数组的例子格式:
Array (
[1] => Array ( [code] => PPJ3 [street] => 34412 Fake Street [city] => Detroit [state] => MI [zip] => 48223 [county] => Wayne [cost] => 432.00 )
[2] => Array ( [code] => PLK3 [street] => 73517 Fake Street [city] => Detroit [state] => MI [zip] => 48223 [county] => Wayne [cost] => 54.00 )
[3] => Array ( [code] => HYK2 [street] => 55224 Fake Street [city] => Detroit [state] => MI [zip] => 48208 [county] => Wayne [cost] => 345.00 )
)
我想设置一个隐藏字段只有代码值,并将它逗号分隔。 该阵列还需要通过进行循环,因为它总是会改变。 这是我想什么它看起来像:
$ myHiddenField = PPJ3,PLK3,HYK2
什么是编码这种简单的方式?
只要你可以参考原数组..
<?PHP $myHiddenField = array(); foreach($array as $row) { $myHiddenField [] = $row['code']; } ?>
或为CSV
<?PHP foreach($array as $row) { $myHiddenField .= ",".$row['code']; } $myHiddenField = substr($myHiddenField,1); ?>
会有array_column功能是PHP 5.5,你将能够做到这一点
$myHiddenField = implode(',', array_column($yourMainArray, 'code'));
现在,你必须使用自己的循环
$values = array();
foreach ($yourMainArray as $address)
{
$values[] = $address['code'];
}
$myHiddenField = implode(',', $values);
那么,什么是错的,使用一个循环?
$myHiddenField = '';
$c = count($array);
for($i=0;$i<$c;$i++){
if($i == $c -1){
$myHiddenField .= $val['code'];
}else{
$myHiddenField .= $val['code'].', ';
}
}
如果您使用PHP 5.3+:
$tmp = array_map(function($v){return($v['code']);}, $array);
$myHiddenField = implode(', ', $tmp);