Home > database >  How can I split a php array column into two
How can I split a php array column into two

Time:11-19

I have been unable to find any help online that addresses this precise issue. I have extracted data from a mysql table in the form of a standard 2-dimensional php array. One of the column headings is 'name' with the first and last names separated by a space eg 'John Smith'. What I want to do is, within the array (not in the table), to replace the 'name' column with two columns: 'firstname' eg 'John' and 'lastname' eg 'Smith'. I have tried extracting the 'name' column using the php function 'array_column()' and using a foreach loop with the 'explode()' function but that just gives me a sub-array of names. What I want is the whole array but with the 'name' column changed to 'firstname' and 'lastname' for all records. How could I do it?

CodePudding user response:

You should consider adding some examples or the code you have tried. The example below will preserve everything you have in the array along with the name, but it will create a new array and put all the values in it.

<?php

$data = [
    [ 'name' => 'John Doe' ],
    [ 'name' => 'Jane Doe' ],
    [ 'name' => 'Adam Jensen' ],
    [ 'name' => 'Seann Willam Scott' ]
];

$newData = \array_map(function(array $record) {
    if (!isset($record['name']) || empty($record['name'])) { return false; } //just in case there's no name in the record
    $parts = \explode(' ', $record['name']);

    // Last name is usually the last part, right?
    // Poping the last element will modify the $parts array, leaving just the first names
    $record['lastname'] = \array_pop($parts);
    $record['firstname'] = \join(' ', $parts);
    
    // Removing the original name field
    unset($record['name']);
    return $record;
}, $data);

$newData = \array_filter($newData); // removing false values, for when there's no name in the record

You can probably have better performance if you do the split on select from your DB.

CodePudding user response:

I believe I have solved the problem - largely through trial and error! The method now looks like this:

$authors = $this->author_model->get('name');
        $authors_sort = array();
        foreach ($authors as $author) {
            $parts = explode(' ',$author['name']);
            $lastname = array_pop($parts);
            $author['lastname'] = $lastname;
            $authors_sort[] = $author;
        }
        return $authors_sort;

and does exactly what I want.

  • Related