3

I have below result from MySQL, PDO search - but I am not able to find suitable answer to make the arrays - to single array, insted of branched array.

   <?php

$dataResult = array("abcdef", "People 1 - 123-456-7890
People 2 - 
People 3 - Abcdef Jack
People 4 _ Defjkl Smack ");


foreach($dataResult as $result){
    if(strstr($result, PHP_EOL)){
        $dataResultArray[] = explode(PHP_EOL, $result);
    } else {
        $dataResultArray[] = $result;
    }

    
}
print_r($dataResultArray);

I am expecting the below result, against what I get is below.

Expected:

abcdef
People 1 - 123-456-7890
People 2 - 
People 3 - Abcdef Jack
People 4 _ Defjkl Smack

Output:

Array
(
    [0] => abcdef
    [1] => Array
        (
            [0] => People 1 - 123-456-7890
            [1] => People 2 - 
            [2] => People 3 - Abcdef Jack
            [3] => People 4 _ Defjkl Smack 
        )

)

2 Answers 2

4

PHP have a nice function for this case: array_walk_recursive:

// your multi-dimensional-array
$array = [
    'item1' => 'value1',
    'item2' => 'value2',
    'item3' => [
        'item3a' => 'value3',
    ],
    'item4' => [
        [
            'item4a' => [
                'value4',
                'value5',
            ],
        ]
    ]
];

array_walk_recursive($array, function($a) use (&$new) { $new[] = $a; });
print_r($new);

output

Array
(
    [0] => value1
    [1] => value2
    [2] => value3
    [3] => value4
    [4] => value5
)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use recusice function to convert multidimensional arrays to single array.


function filter($array)
{
    static $newArray;
    if (is_array($array)):
        array_map('filter', $array);
    else:
        $newArray[] = $array;
    endif;

    return $newArray;
}


$array = [
    'isim' => 'Şahin',
    'soyisim' => 'ERSEVER',
    'yabanci_dil' => [
        'tr' => 'Türkçe',
    ],
    'languages' => [
        [
            'php' => [
                'codeigniter',
                'laravel',
                'symfony'
            ],
            'javascript' => [
                'vuejs',
                'react' => [
                    'react',
                    'react-native'
                ]
            ]
        ]
    ]
];


print_r(filter($array));

Result:

Array
(
    [0] => Şahin
    [1] => ERSEVER
    [2] => Türkçe
    [3] => codeigniter
    [4] => laravel
    [5] => symfony
    [6] => vuejs
    [7] => react
    [8] => react-native
)

1 Comment

did not work - please check -

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.