问题
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?
回答1:
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); ?>
回答2:
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);
回答3:
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);
来源:https://stackoverflow.com/questions/16126664/multidimensional-array-implode