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.

RobbTe
  • 385
  • 4
  • 19

2 Answers2

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);
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • 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 – RobbTe Jul 04 '17 at 14:46
  • Works, but shouldn't there be a comma after each "inner" array? – RobbTe Jul 04 '17 at 15:48
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>";
?>
RïshïKêsh Kümar
  • 4,734
  • 1
  • 24
  • 36