1

这是我正在处理的多维数组的示例格式:

 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

对此进行编码的简单方法是什么?

4

3 回答 3

2

只要您可以引用原始数组..

<?PHP
$myHiddenField = array();
foreach($array as $row) {
    $myHiddenField [] = $row['code'];
}
?>

或对于 csv

<?PHP
foreach($array as $row) {
    $myHiddenField .= ",".$row['code'];
}
$myHiddenField = substr($myHiddenField,1);
?>
于 2013-04-21T00:21:05.347 回答
2

会有array_column函数是PHP 5.5,你就能做到这一点

$myHiddenField = implode(',', array_column($yourMainArray, 'code'));

现在你必须使用你自己的循环

$values = array();
foreach ($yourMainArray as $address)
{
  $values[] = $address['code'];
}
$myHiddenField = implode(',', $values);
于 2013-04-21T00:24:10.953 回答
0

那么使用循环有什么问题呢?

$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);
于 2013-04-21T00:23:37.967 回答