0

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')
),
3
  • 1
    Use explode to make a numeric array, then convert that to an associative array. Commented Jul 6, 2014 at 2:52
  • I can see no difference in all the 3 inner arrays.! Commented Jul 6, 2014 at 2:53
  • explode + array_combine Commented Jul 6, 2014 at 2:54

2 Answers 2

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

1 Comment

Awesome. Used array_combine. Thanks!
0

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

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.