1

my array:

Array
(
[patient_id] => Array
        (
            [0] => 23
            [1] => 24
            [2] => 25
        )

[fullname] => Array
    (
        [0] => Jhon Sena
        [1] => Mary Sena 
        [2] => Carter Sena
    )

[type] => Array
    (
        [0] => pdf
        [1] => pdf
        [2] => pdf
    )

[textarea_text] => Array
    (
        [0] => text
        [1] => text2
        [2] => text3
        )

)

what i'm triying to get:

Array
(
    [patient_id] => 23
    [fullname] => Jhon Sena
    [type] => pdf
    [textarea_text] => text
)
Array
(
    [patient_id] => 24
    [fullname] => Mary Sena
    [type] => pdf
    [textarea_text] => text2
)    
Array
    (
    [patient_id] => 25
    [fullname] => Carter Sena
    [type] => pdf
    [textarea_text] => text3
)

i've been trying with many php flatten array functions pointed here in another questions but i could not get the desired results, can you please point me in the right direction?

For example this flatten function:

function flatten($ar) {
        $toflat = array($ar);
        $res = array();

        while (($r = array_shift($toflat)) !== NULL) {
            foreach ($r as $v) {
                if (is_array($v)) {
                    $toflat[] = $v;
                } else {
                    $res[] = $v;
                }
            }
        }

        return $res;
    }

Throws me this result with no keys:

    Array
(
    [0] => 23
    [1] => 24
    [2] => 25
    [3] => Jhon Sena
    [4] => Mary Sena
    [5] => Carter Sena
    [6] => pdf
    [7] => pdf
    [8] => pdf
    [9] => text
    [10] => text2
    [11] => text3
)

.............................

3
  • i've been trying with many php flatten array functions pointed here in another questions ->Then please post your attempted code in your question, to make us believe in you that you really tried something. Commented Mar 4, 2021 at 11:47
  • The issue is that you really aren't looking to simply flatten this. You need a custom function that builds that new array per your specification (where every numeric index in inner arrays represents an element of the same subarray in the result). Commented Mar 4, 2021 at 11:49
  • i've edited the post with an example of what i'm been doing Commented Mar 4, 2021 at 11:57

1 Answer 1

2

You can do it via simple foreach()

$fialArray = [];

foreach($array as $key=>$value){
    foreach($value as $k=>$val){
        $fialArray[$k][$key] = $val;
    }
}

print_r($fialArray);

Output : https://3v4l.org/qqgp7

Sign up to request clarification or add additional context in comments.

1 Comment

@elgranchuchu glad to help you. Please have a look to the edited solution. It's more efficient now

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.