我有这个返回数组
$leaseArray = Array ( [0] => Array ( [LeaseNumber] => OL/2011/0343 ) [1] => Array ( [LeaseNumber] => 184 ) [2] => Array ( [LeaseNumber] => OL/2011/0118 ) [3] => Array ( [LeaseNumber] => OL/2016/1759 ) [4] => Array ( [LeaseNumber] => OL/2013/0858 ) [5] => Array ( [LeaseNumber] => OL/2012/0535 ) [6] => Array ( [LeaseNumber] => OL/2017/2208 ) [7] => Array ( [LeaseNumber] => 2355 ) )
我想将LeaseNumber的所有值保存到一个逗号分隔的字符串中
比如$string = "OL/2011/0343 , 184 , OL/2011/0118 , OL/2016/1759"
请帮帮我
$lease = array();
for($i=0;$i<=count($leaseArray); $i++){
$lease = $leaseArray[$i]['LeaseNumber'];
}
答案 0 :(得分:3)
如果你想要一个单行,那么这就是
$csv = implode(' , ', array_column($a, 'LeaseNumber'));
正如我在评论中所说,1行,2个函数调用。
答案 1 :(得分:0)
如果你想要一个单行,那么这可以工作:
$csv = implode( ' , ', array_map( function( $a ){ return $a[ 'LeaseNumber' ]; }, $leaseArray ) );
展开:
$csv = implode( ' , ', // step 2: implode on ' , ': space-comma-space
array_map( // step 1: pass $lease array into array_map so that we can get a new array
function( $a ){ return $a[ 'LeaseNumber' ]; }, // Accept each array in $a and only return the LeaseNumber. array_map will build a new array out of just these values
$leaseArray // the array to be processed
)
);
实质上,这与:
相同$csv = implode( ' , ', array_column( $a, 'LeaseNumber' ) );
但array_map()
允许您在输出/返回之前转换数据。
答案 2 :(得分:0)
单行很棒但有时难以阅读。如果你想坚持你在这里有一些注意事项
<?php
$array = array(array("LeaseNumber" => "OL/2011/0343"), array("LeaseNumber"=> 184 ), array("LeaseNumber"=> "OL/2011/0118") , array("LeaseNumber"=> "OL/2016/1759"), array("LeaseNumber"=> "OL/2013/0858"), array("LeaseNumber"=> "OL/2012/0535"), array("LeaseNumber"=> "OL/2017/2208"), array("LeaseNumber"=> 2355));
$lease = array();
//Not equal to the count it starts at 1 not 0
for($i=0;$i<count($array); $i++){
//lease is an array add to the index not overwrite
$lease[] = $array[$i]['LeaseNumber'];
}
//You needed to finish with this
$csv = implode(", ",$lease);
echo $csv;
在这种情况下转向foreach会让生活更轻松:
$lease = array();
foreach($array as $obj){
$lease[] = $obj["LeaseNumber"];
}