如何使2级数组变为asimple数组

时间:2019-05-30 12:27:40

标签: php arrays

我有一个像这样的数组:

[12601] => Array (
        ['docUpload'] => html dom.txt
)

[12602] => Array (
        ['docUpload'] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
)
[12603] => Array (
        ['docUpload'] => 
)

如何获得它:

12601 => html dom.txt
12602 => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt

你能帮我吗?

4 个答案:

答案 0 :(得分:1)

您必须使用foreach()

$final_array = array();

foreach($array as $key=>$val){
   $final_array[$key]= $val['docUpload'];
}

输出:-https://3v4l.org/cP0TOhttps://3v4l.org/DRjNn

如果子数组索引是动态的,则

$final_array = array();

foreach($array as $key=>$val){
  $final_array[$key]= array_values($val)[0];
}

print_r($final_array);

输出:-{https://3v4l.org/4tDmW

注意:- 使用array_filter()删除空索引(第一答案第二输出链接)

答案 1 :(得分:1)

使用array_column()获取值,然后将它们与array_combine()array_keys()组合。

$values = array_column($array, 'docUpload');
$newArray = array_combine(array_keys($array), $values);

答案 2 :(得分:0)

您可以通过foreach()

遍历数组

步骤:

1)取一个新的空白数组。我们将结果附加到此。

2)如果数组不为空,请在数组上循环foreach

3)使用键值对。密钥是必需数组中的id

4)值是一个以键docUpload作为文档名称的数组。

5)用idvaluedocUpload)附加新元素。

6)结果数组将是一维数组。

最终密码:

$arr = [];
$arr[12401] = ['docUpload' => ''];
$arr[12601] = ['docUpload' => 'html dom.txt'];
$arr[12602] = ['docUpload' => 'PYTHON AND DJANGO ARE HUGE IN FINTECH.txt'];
$arr[12603] = ['docUpload' => ''];
$newArr = [];
if (! empty($arr)) {
 foreach ($arr as $id => $docArr) {
  $newArr[$id] = $docArr['docUpload'];
 }
}
echo '<pre>';print_r($newArr);echo '</pre>';

输出:

Array
(
    [12401] => 
    [12601] => html dom.txt
    [12602] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
    [12603] => 
)

Working Link:

答案 3 :(得分:0)

您需要执行以下操作:

foreach ($arrayData as &$value) {
    $value = isset($value['docUpload']) ? $value['docUpload'] : '';
}

这将导致以下数组:

[docUpload] => [
    [12601] => html dom.txt
    [12602] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
];