2

I have the following Array in hand. I have to iterate the following array in order that it will create another array with an output of 0th index of every sub-array on the 0th index of new array and so on.

Current Array

 Array
    (
        [0] => Array
            (
                [0] => 1
                [1] => 2
                [2] => 3
            )

        [1] => Array
            (
                [0] => 1
                [1] => 2
                [2] => 3
            )

        [2] => Array
            (
                [0] => 1
                [1] => 2
                [2] => 3
            )

    )

Desired Output

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

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

        [2] => Array
            (
                [0] => 3
                [1] => 3
                [2] => 3
            )

    )
0

3 Answers 3

5

For PHP versions >= 5.5.0 you have the array_column() function:

$newArray = array_column(
    $oldArray,
    0
);

For earlier versions of PHP, you can use array_map()

$column = 0;
$newArray = array_map(
    function ($value) use ($column) {
        return $value[$column];
    },
    $oldArray
);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Mark you got me out of a big mess. Appreciated
0

That's not allot of info to work with...so, something like:

$newArray = [];
foreach($topArray as $idxTop => $valTop){
  if(is_array($valTop)){($newArray[] = $valTop[0];}
}

Comments

0
$input = [
    0 => [1, 2, 3],
    1 => [1, 2, 3],
    2 => [1, 2, 3]
];

$output = [
    array_column($input, 0),
    array_column($input, 1),
    array_column($input, 2)
];

print_r($output);

// Output:
// 
// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => 1
//             [2] => 1
//         )

//     [1] => Array
//         (
//             [0] => 2
//             [1] => 2
//             [2] => 2
//         )

//     [2] => Array
//         (
//             [0] => 3
//             [1] => 3
//             [2] => 3
//         )

// )

Comments

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.