Multidimensional Array Implode [duplicate]

2019-08-04 05:11发布

This question already has an answer here:

Here is an example format of the multidimensional array I'm dealing with:

 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 ) 
 )

I am trying to set a hidden field to only the code values and have it comma separated. The array would also need to be looped through because it will always change. This is what I would like for it to look like:

$myHiddenField = PPJ3, PLK3, HYK2

What is a simple way of coding this?

3条回答
来,给爷笑一个
2楼-- · 2019-08-04 05:31

as long as you can reference the original array ..

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

or for a csv

<?PHP
foreach($array as $row) {
    $myHiddenField .= ",".$row['code'];
}
$myHiddenField = substr($myHiddenField,1);
?>
查看更多
Luminary・发光体
3楼-- · 2019-08-04 05:35

There will be array_column function is PHP 5.5, you will be able to do this

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

For now you have to use your own loop

$values = array();
foreach ($yourMainArray as $address)
{
  $values[] = $address['code'];
}
$myHiddenField = implode(',', $values);
查看更多
小情绪 Triste *
4楼-- · 2019-08-04 05:52

So what's wrong with using a loop ?

$myHiddenField = '';
$c = count($array);

for($i=0;$i<$c;$i++){
  if($i == $c -1){
     $myHiddenField .= $val['code'];
  }else{
     $myHiddenField .= $val['code'].', ';
  }
}

If you're using PHP 5.3+:

$tmp = array_map(function($v){return($v['code']);}, $array);
$myHiddenField = implode(', ', $tmp);
查看更多
登录 后发表回答