多维数组内爆

时间:2013-04-21 00:16:54

标签: php multidimensional-array implode

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

 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

这是一种简单的编码方式吗?

3 个答案:

答案 0 :(得分:2)

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

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

或csv

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

答案 1 :(得分:2)

将有array_column函数是PHP 5.5,您将能够执行此操作

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

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

$values = array();
foreach ($yourMainArray as $address)
{
  $values[] = $address['code'];
}
$myHiddenField = implode(',', $values);

答案 2 :(得分: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);