1

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?

2
  • 1
    Is the user guaranteed to input that exact format every time? Commented Jun 28, 2017 at 12:37
  • Yes, this format will always be this. The user will be myself, and a small group of members who I can instruct how to enter. A placeholder on the textarea will also help. Commented Jun 28, 2017 at 12:39

4 Answers 4

3

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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]
    ];
}

Comments

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

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

Comments

1

Here you go

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

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.