php array

hi guys

trying to seperate a string into array but can’t think

[PHP]
$string=“perri~1~returned~today?”;
$organizer=array(“Name”,“QTY”,“Status”,“when”);

//i want the array to be like:

//$data[0][NAME]=“perri”;
//$data[0][QTY]=“1”;
//$data[0][Status]=“returned”;
//$data[0][when]=“today”;

//and then $data[1] …
?>[/PHP]

so i want to use the organizer array as sub-array keys and then use the string as values for those sub-array keys

From what’s in your comments I’m assuming there are multiple sets of data that need to be assigned. As I don’t know how you’re storing these sets of data, I will show you the code to get the result of the example data given, and if you let me know how you’re storing the rest I’ll show you how you can adapt it.

[php]$string=“perri~1~returned~today?”;
$organizer=array(“Name”,“QTY”,“Status”,“when”);

$output = array_combine($organizer,explode(’~’,$string));[/php]

This is a compact & lightweight version, let me know if you want a broken down, commented version.

I actually wrote a whole damn function but it practically does the same thing you mentioned in a line. Lol. Thanks bro.

I am storing the data as a string in database. I simply wanted to pull the string and break it down.

If you’re interested, the following is what I wrote to do the same thing you mentioned. But I like your’s better. Its easier.

[php]
//explode any array based on string and the array organizier
function explodeArray($string,$organizer){
$eachElement=explode("?",$string);

for($x=0; $x<count($eachElement); $x++){
		$eachElement_ar[]=explode("~",$eachElement[$x]);
}

$counter=1;
foreach($eachElement_ar as $eachElement_ar_element){
	
	for($x=0; $x<count($eachElement_ar_element); $x++){
		if($eachElement_ar_element[$x]!=""){
		$output[$counter][$organizer[$x]] = $eachElement_ar_element[$x];
		}
	}
	$counter++;
}
return $output;
}

[/php]

Right, as a guess your data is stored as a string variable such as this:

$info = "perri~1~returned~today?jane~2~bought~yesterday?bob~2~bought~today"

Again, I’m going for the compact version, let me know if you want a more broken down one:
[php]$info = “perri~1~returned~today?jane~2~bought~yesterday?bob~2~bought~today”;
$organiser = array(“name”,“qty”,“status”,“when”);
$info = explode(’?’,$info);
$output = array();
foreach($info as $key => $data)
{
$data = explode(’~’,$data);
$output[$key] = array_combine($organiser,$data);
}

echo ‘

’;
print_r($output);
echo ‘
’;
[/php]
Sponsor our Newsletter | Privacy Policy | Terms of Service