PHP生成一个包含许多值的数组索引并删除空数组值

时间:2016-04-27 17:42:10

标签: php arrays

我有这个数组:

[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;
    }
}

怎么做?

5 个答案:

答案 0 :(得分:3)

获得精确的数组输出:

$result['docValues'][key($values['docs'])] =
    array_filter(array_column($values['docs'], 0));
  • 获取第一个密钥,将其用作key()
  • 的新密钥
  • 使用array_column()
  • 获取0索引中所有值的数组
  • 使用array_filter()
  • 删除空元素

答案 1 :(得分:1)

只需这样做:

您的数组

$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('&lt;br/&gt;', array_filter(array_column($arr['docs'], 0)));
print_r($output);

<强>解释

  • key = key function返回第一个索引。

  • implode = 使用<br/>

  • 的分隔符折叠所有数组项
  • array_filter = 使用回调过滤数组的值 功能

  • array_column = 返回输入中单个列的值 阵列

<强>结果:

Array
(
    [docValues] => Array
        (
            [indexone] => P008062518<br/>0000141334<br/>P006871638<br/>0000910067
        )

)

答案 2 :(得分:1)

如果您的第一个数组被称为$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

如果这对您有用,请告诉我。

答案 3 :(得分:1)

这应该适合你:

$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

答案 4 :(得分:0)

使用array_filter()功能。如果在array_filter中传递数组,则删除所有空数据和空数据