0

Almost similar questions are repeated.

I am updating and fetching string from database for different issues.

lets say after fetching value from database one of my variable $str looks like one of the below

$str = "1:1,2:1,3:2,5:6";

or

$str = "1|1,2|1,3|2,5|6";

or

$str = "1=1,2=1,3=2,5=6";

how can I convert anyone or almost different string to an associative array in PHP

thanks in advance. I tried for an answer but didnt find anything similar.

code i tried to make it an associative array

$firstArr = explode(',', $str);

foreach (firstArr as $value) {
    $secondArr = explode(':', $value);
}
4

4 回答 4

1

Try this:

$final_array = Array();
$str = "1|1,2|1,3|2,5|6";
$arr1 = explode(",", $str);

// this gives $arr1 as 
// array(4) { [0]=> string(3) "1|1" [1]=> string(3) "2|1" [2]=> string(3) "3|2" [3]=> string(3) "5|6" } 
// iterate through $arr1 and further split it on | using explode function
foreach ($arr1 as $k=>$v){
    $arr2 = explode("|", $v);
    // $arr2 would be like 
    // array(2) { [0]=> string(1) "1" [1]=> string(1) "1" }  etc.
    $final_array[$arr2[0]] = $arr2[1];
}

print_r($final_array);
// gives Array ( [1] => 1 [2] => 1 [3] => 2 [5] => 6 ) 

But as Sylvain mentioned, you might also want to look into your database normalization part.

于 2013-08-08T18:23:01.380 回答
0

Using PHP's str_split and explode functions:

$str = "1:1,2:1,3:2,5:6";
$split = str_split($str, 4);
$explode = explode(":", $split);
$array = array();
for($i = 0; $i <= count($explode); $i++)
{
    $array[] = ($explode[$i]);
}

After every comma (4 characters), the string splits. Then after every : explode the value. And then put that in an array.

于 2013-08-08T18:26:56.280 回答
0
/**
 * Converts CSV to associative array
 *
 * @param string $str
 *
 */
function csv2associative_array($str) {
   $csv_items = preg_split('/\s*\,\s*/',$str);
   $items = array();
   foreach ($csv_items as $x => $csv_item) {
      list($key,$value) = preg_split('/\W/',$csv_item,2);
      if ($key && $value) {
         $items[$key] = $value;
      }
      else {
         trigger_error("keys/values not found for item #$x");
      }
   }
   return $items;
}
于 2013-08-08T18:31:07.953 回答
0

A) You shouldn't be storing such strings in your database in the first place. It's a code smell. Among other things it suggests you're not normalizing your schema enough.

B) If you really need to work with such strings, you can for example do.

$string = "1|1,2|1,3|2,5|6";
$tempArray = explode(",", $string);
$finalArray = array();

foreach ($tempArray as $pair) {
    $subArray = explode("|", $pair);
    $finalArray[$subArray[0]] = $subArray[1];
}

This will result in

Array ( [1] => 1 [2] => 1 [3] => 2 [5] => 6 )

if you print_r it.

Or you can use other string functions like substring, etc. to get key and value out of the $pairs.

于 2013-08-08T18:33:11.547 回答