0

hi all,

i am new to php, i have a database field called results in that i am inserting a string something like this "category_name:-abs43;c1-abs43;types:-abs43;t1"


now i want to put this string into an array, i have used the delimiter '-abs40;' as u can see in the string.

the array should be like this Array([category_name:]=>c1[types:]=>t1)

how can i accomplish this

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by mschroeder
0

try:

function toArray($str, $delimiter=',', $assoc=false)
{
	$data=explode($delimiter,$str);
	if(TRUE===$assoc)
	{
		$temp=array();
		$i=-1;
		$limit=count($data);
		while(++$i < $limit)
		{
			$key=$data[$i];
			$val=$data[++$i];
			$temp[ $key ]=$val;
		}
		unset($data);
		$data=$temp;
	}
return $data;
}

$str="category_name:-abs43;c1-abs43;types:-abs43;t1";
$result=toArray($str,'-abs43;',TRUE);
print_r($result);
0
<?php
/**
 * Explodes the supplied string by the supplied delimiter
 * and reassembles based on each even key getting the next odd value
 *
 * @param String $string
 * @param String $delimiter
 * @return Array
 */ 
function toArray($string, $delimiter){
	$pieces = explode($delimiter, $string);
	$temp = array();
	foreach($pieces as $k => $v){
		if( ($k&1) == 0 ){
			$temp[$v] = (isset($pieces[$k+1]) ? $pieces[$k+1] : '');
		}
	}
	return $temp;
}

print_r(toArray($string,'-abs43;'));
//Array ( [category_name:] => c1 [types:] => t1 )

At 100 iterations the difference is in the ten thousandths of a second.
At 10000 iterations its about 30% faster.

If you know for sure your array will ALWAYS have an even amount of value, removing the isset check and the ternary operator ( ?: ) will make it just over 50% faster.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.