0

Let's say I have an string like

$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|SEM";

and i want an array like:

array( array("title"=>"BKL", "value"=>bkl),
array("title"=>"EXH", "value"=>exh),
array("title"=>"FFV", "value"=>ffv),
array("title"=>"LEC", "value"=>lec),
array("title"=>"AUE", "value"=>aue),
array("title"=>"SEM", "value"=>SEM),
); 

I have found a solution here: How to create particular array from string in php but this is giving me an array like:

Array
(
    [BKL] => bkl
    [EXH] => exh
    [FFV] => ffv
    [LEC] => lec
    [AUE] => aue
    [SEM] => sem
)

Thanks a lot.

2 Answers 2

1

Use Your String which you want to display in foreach with key and values:

Demo: https://eval.in/827426

<?php

$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";

$final = array();

foreach (explode(',', $str) as $pair) {
  list($key, $value) = explode('|', $pair);
  $final[] = ['Title'=>$key .',', 'Value'=>$value];
}

echo "<pre>";
print_r($final);
echo "</pre>";
?>
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, i guess however a comma is missing after each inner array?
Thanks for getting back to me, but i meant a comma after the ) from the inner array, like [0] => Array ( [Title] => BKL [Value] => bkl ),
@RobbTe ... Here if you try Your self then it easy, then you can easily understand whats going on here ,
Hi, thanks.. i did find how to put an extra comma within the array, but i am not sure how to put a comma after the ) from the inner array. So like (see the last comma) [0] => Array ( [Title] => BKL [Value] => bkl ),
in the end of aaray you get the comma ??
|
1

All you need to do is change the way the array is built up...

$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";

$final = array();

foreach (explode(',', $str) as $pair) {
  list($key, $value) = explode('|', $pair);
  $final[] = ['title'=>$key, 'value'=>$value];
}

print_r($final);

2 Comments

Awesome thanks, i just wasn't sure about how the array was built in the first place. Most of the time more easy than you think:) thanks
Works, but shouldn't there be a comma after each "inner" array?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.