I have some data in the database, in this format:
Description~Level||Description~Level||
I want to transform this into an array where description is the Key & Level the value of the array.
$perso1 = explode('||', $myLevels['perso']);
$perso = array_slice($perso1, 0 , -1);
so far ive done this and it return that :
Array ( [0] => ffghtr~54644
[1] => ffghtr~54644
[2] => ffghtr~54644
[3] => ffghtr~54644
[4] => ffghtr~54644
[5] => ffghtr~54644 )
Now I cannot find a way to replace the array keys (0,1,2,etc) by my description.
Any idea ?
Thanks very much in advance.
$tmp = explode('||', $myLevels['perso']);
foreach ($tmp as $str) {
// this check is to remove empty elements from the list ..
// because your list ends with "||" there is a last empty element
if(strpos($str, "~") === false) continue;
// split by "~" into $key and $value
list($key, $value) = explode("~", $str, 2);
$result[$key] = $value;
}
print_r($result);
Please note that in the posted example you always have the same key: "ffghtr".
Because array keys are unique, you will end up replacing the content of this key with every iteration, having only the last element as the result.
$array = Array ( [0] => ffghtr~54644
[1] => ffghtr~54644
[2] => ffghtr~54644
[3] => ffghtr~54644
[4] => ffghtr~54644
[5] => ffghtr~54644 )
$new_array = new Array();
foreach($array as $a)
$new_array[(split('~',$a))[0]] = (split('~',$a))[1]
So new_array should be in the form you want. Actually i did not test the code but you got the idea. Please note the array you posted has always the same key: ffghtr.
So yuo'll end up with a new_array of only one element...