Lee
Lee

Reputation: 4323

How can i split an array into a nested array by splitting each element?

My question may not make sense, but after trying all kinds of array_chunk, and explodes, I can't seem to find an easy way to solve my issue.

Ultimately, I have a textarea that I want to be able to enter data like this:

<textarea>
    Song 1 by Artist 1
    Song 2 by Artist 2
    Song 3 by Artist 1
    Song 4 by Artist 3
    Song 5 by Artist 3
</textarea>

I want to ultimately create an array that I can filter and loop out, and grab each song title and artist title, and have a nested array.

So far, I can use explode( "\n", $source) to create a simple array:

array (size=5)
  0 => string 'Song 1 by Artist 1' (length=19)
  1 => string 'Song 2 by Artist 2' (length=19)
  2 => string 'Song 3 by Artist 1' (length=19)
  3 => string 'Song 4 by Artist 3' (length=19)
  4 => string 'Song 5 by Artist 3' (length=18)

But I want to now further create an array inside this for each song title and artist title so it will look like:

array (
  0 => array(
    'title' => 'Song 1',
    'artist' => 'Artist 1
  ),
  1 => array(
    'title' => 'Song 2',
    'artist' => 'Artist 2
  )
  etc.

How can I expand the initial explode function to be able to loop out the final array values as a list?

Upvotes: 1

Views: 405

Answers (4)

CodeGodie
CodeGodie

Reputation: 12132

Here you go

$arr = explode("\n", $string);
foreach ($arr as $item) {
    $set = explode(" by ", $item);
    $result[] = array_combine(["title", "artist"], $set);
}
var_dump($result);

Upvotes: 1

James Lalor
James Lalor

Reputation: 1246

$songList = explode( "\n", $source);

foreach($songList as &$value) {
    $interim = explode(" by ", $value);
    $value = ['title' => $interim[0], 'artist' => $interim[1]];
}

Upvotes: 1

Dolly Aswin
Dolly Aswin

Reputation: 2794

Here I use functional in PHP to extract data

$arrays = [
    "Song 1 by Artist 1",
    "Song 2 by Artist 2",
    "Song 3 by Artist 1",
    "Song 4 by Artist 3",
    "Song 5 by Artist 3",
];
$result = [];

array_walk($arrays, function ($data) use (&$result) {
    $fields = explode(' by ', $data);
    $result[] = [
        "title"  => $fields[0],
        "artist" => $fields[1],
    ];
});

print_r($result);

Upvotes: 3

timiTao
timiTao

Reputation: 1413

Then you need split by $row = explode(' by ', $array) with code

$mainArray = explode("\n", $text);
$list = [];
foreach ($mainArray as $oneRow) {
    $row = explode(' by ', $oneRow);
    $list[] = [
        'artist' => $row[1],
        'title' => $row[0]
    ];
}

Upvotes: 1

Related Questions