0

I have an array like this:

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

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

How to get it like this:

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

can you help me please?

Qirel
  • 25,449
  • 7
  • 45
  • 62
Dave
  • 99
  • 7

3 Answers3

1

Use array_column() to get the values, then combine them with array_combine() and array_keys().

$values = array_column($array, 'docUpload');
$newArray = array_combine(array_keys($array), $values);
Qirel
  • 25,449
  • 7
  • 45
  • 62
  • Will it filter empty string? maybe add `array_filter` after the `array_combine` – dWinder May 30 '19 at 12:50
  • This does not do any filtration, no. If OP wants to filter empty strings, then yes, you just add `array_filter()` to `$newArray`. – Qirel May 30 '19 at 12:51
  • I know - but that what the OP post in his desire output... (I just recommend add that in your post) – dWinder May 30 '19 at 12:58
0

You can loop over the array by foreach()

Steps:

1) Take a new blank array. We are appending our results into this.

2) If the array is not empty, loop over the array by foreach

3) Use key value pairs. Key is the id in required array.

4) Value is an array with key docUpload to be the document name.

5) Append new element with id and value (docUpload).

6) Resulting array will be a single dimensional array.

Final Code:

$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>';

Output:

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

Working Link:

Pupil
  • 23,834
  • 6
  • 44
  • 66
  • it s a dynamic array..so i vcant use fixed id like u suggested. – Dave May 30 '19 at 12:38
  • i get the array from a foreach loop....like such foreach($_FILES['docUpload']["name"] AS $key=>$file) { The array i provided above in the code is the $file } – Dave May 30 '19 at 13:08
0

You need to do as follows:

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

It will result in following array:

[docUpload] => [
    [12601] => html dom.txt
    [12602] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
];
Dhara Bhatti
  • 239
  • 2
  • 8