stueynet
stueynet

Reputation: 1102

Converting strings to arrays with keys PHP

I am trying to take an array with delimited strings and turn it into a multi dimensional array with named keys. Its easy to do it with numbers for keys but in my case I want to assign a key to each. The keys are slug, title, and type which correspond to keys 0,1,2 in each array.

    array(
        'thisslug|This title|text',
        'thatslug|Thats title|text',
        'anotherslug|Another title|dropdown',
    );

I want to end up with

array(
   array('slug' => 'thisslug', 'title' => 'this title', 'type' => 'text'),
   array('slug' => 'thisslug', 'title' => 'this title', 'type' => 'text'),
   array('slug' => 'thisslug', 'title' => 'this title', 'type' => 'text')
),

Upvotes: 0

Views: 101

Answers (2)

michikot
michikot

Reputation: 142

do a for loop on your current array and explode the content .

$arr = array(
    'thisslug|This title|text',
    'thatslug|Thats title|text',
    'anotherslug|Another title|dropdown',
);

$newArr = array();

for($i = 0; $i < count($arr); $i++) {
    $strArr = explode('|', $arr[$i]);
    $newArr['slugs'] = $strArr[0];
    $newArr['title'] = $strArr[1];
    $newArr['type'] = $strArr[2];
}

Upvotes: 0

Barmar
Barmar

Reputation: 781028

$result = array();
foreach ($array as $string) {
    $row = explode('|', $string); // Explode the string
    // Convert it to associative
    $result[] = array('slug' => $row[0], 'title' => $row[1], 'type' => $row[2]);
}

Or use array_combine:

$keys = array('slug', 'title', 'type');
foreach ($array as $string) {
    $row = explode('|', $string); // Explode the string 
    $result[] = array_combine($keys, $row);
}

Upvotes: 3

Related Questions