我有这个数组:
[docs] => Array
(
[indexone] => Array ( [0] => P008062518 )
[indextwo] => Array ( [0] => )
[indexthree] => Array ( [0] => 0000141334 )
[indexfour] => Array ( [0] => P006871638 )
[indexfive] => Array ( [0] => 0000910067 )
[indexsix] => Array ( [0] => )
)
我需要以这个结束,从给定的键中提取所有值:
[docValues] => Array
(
[indexone] => Array ( P008062518, 0000141334, P006871638, 0000910067 )
)
我尝试这个循环,但我以相同的数组结构结束:
foreach($values as $key => $data)
{
if(array_key_exists('docs', $data) )
{
$filtered = array_filter($data['docs'], function($var) { return !empty($var);});
$numDocs = array_values($filtered);
$values[$key]['docValues'] = $numDocs;
}
}
怎么做?
要获得确切的数组输出:
$result['docValues'][key($values['docs'])] =
array_filter(array_column($values['docs'], 0));
- 获取第一个密钥,以将其用作新密钥,
key()
- 获取 0 索引中所有值的数组,
array_column()
- 使用
array_filter()
删除空元素
如果您的第一个数组称为 $docArray
,那么您可以执行以下操作:
$docValuesArray = array();//declaring the result array
$indexoneArray = array();//declaring the array you will add values
//to in the foreach loop
foreach ($docArray as $value)
{
$indexoneArray[] = $value[0];//giving each of the values
//found in $docArray to the $indexoneArray
}
$docValueArray[] = $indexoneArray;//adding the $indexoneArray
//to the $docsValueArray
让我知道这是否适合您。
这应该可以为您解决问题:
$docs = [
'indexone' => ['P008062518'],
'indextwo' => [ ],
'indexthree' => ['0000141334'],
'indexfour' => ['P006871638'],
'indexfive' => ['0000910067'],
'indexsix' => [ ],
];
$allDocs = array();
foreach($docs as $key => $doc) {
$docString = implode("<br>",$doc);
if (empty($docString)) {
continue;
}
$allDocs[] = $docString;
}
$allDocsString = implode("<br>",$allDocs);
echo($allDocsString);
P008062518 0000141334
P006871638
0000910067
只需这样做:
您的阵列
$arr = array("docs" =>
array(
'indexone' => array('P008062518'),
'indextwo' => array(''),
'indexthree' => array('0000141334'),
'indexfour' => array('P006871638'),
'indexfive' => array('0000910067'),
'indexsix' => array('')
)
);
过程:
echo '<pre>';
$index = key($arr["docs"]);
$output['docValues'][$index] = implode('<br/>', array_filter(array_column($arr['docs'], 0)));
print_r($output);
解释:
- key
= key 函数 返回第一个索引。
内爆 = 折叠所有数组项,分隔符为
<br/>
array_filter = 使用回调过滤数组的值功能。
array_column = 返回输入中单个列的值数组。
结果:
Array
(
[docValues] => Array
(
[indexone] => P008062518<br/>0000141334<br/>P006871638<br/>0000910067
)
)
使用array_filter()
函数。 如果在array_filter中传递数组,则删除所有空和空数据记录