OliverSamson43
OliverSamson43

Reputation: 53

Replace each whole row of a 2d array with its first element value

I'm banging my head against what I am sure is a simple fix to re-structure an array. I don't have any choice over how the array is given to me:

Array
(
    [author] => Array
        (
            [0] => John Doe
        )

    [journal] => Array
        (
            [0] => Biology
        )
)

But I need the following:

Array
(
    [author] => John Doe
    [journal] => Biology
)

I've been working on various routes, but my brain doesn't work like this right now.

Upvotes: 1

Views: 57

Answers (3)

mickmackusa
mickmackusa

Reputation: 48100

Isolate and return the first value of each row using array_map(). When provided a single array to iterate, the default behavior is to preserve the original keys.

Code: (Demo)

$array = [
    'author' => ['John Doe'],
    'journal' => ['Biology'],
];

var_export(
    array_map('current', $array)
);

Output:

array (
  'author' => 'John Doe',
  'journal' => 'Biology',
)

Upvotes: 0

scrowler
scrowler

Reputation: 24435

<?php

function reduce_array($array) {
    $new = array();
    foreach($array as $key => $value) {
        $new[$key] = $value[0];
    }
    return $new;
}

?>

Upvotes: 2

Petah
Petah

Reputation: 46060

$result = [];
foreach ($data as $key => $value) {
    $result[$key] = $value[0];
}
var_dump($result);

Upvotes: 3

Related Questions