Jump to content

Variable Variables with arrays


flyingboz

Recommended Posts

Trying to wrap my head around this:


$priority = array('first','second','third');
$properties = array('ToName','FromName,'ToAddr','FromAddr');

a sql query returns a list of elements that I want to map into an array.  The $result array contains associative keys that look like:  first_ToName,first_FromName,secondToName,secondFromName, etc. 

It  seems like the 'variable variable capability of php could do what I want, but I haven't gotten the syntax right to create an array containing all of this information in a loop and, once created, be able to reference as an array each priority's settings.

This would enable me to be able to easily reference all the values for each priority, swap priorities, etc.




Link to comment
https://forums.phpfreaks.com/topic/28145-variable-variables-with-arrays/
Share on other sites

Not sure what else would help.  This is more of a "provide strategy / concept" issue than a "find what's wrong w/ my code" problem.

The $result array looks like this:

$result = array(
'first_ToName'  => 'bob',
            'first_FromName'  => 'operations',
'second_ToName' => 'sally',
'second_FromName' => 'presales'
);
$priority = array('first','second','third');
$properties = array('ToName','FromName','ToAddr','FromAddr');

The question is; how do I build an array from these that lets me easily reference each set of priority's values?
Pointers to references that would provide greater help are welcome.  I'm not trolling for someone to write my code for me.




I am not sure that this is the right syntax for you or not.
[code]
<?php
$priority = array('first','second','third');
$properties = array('ToName','FromName','ToAddr','FromAddr');

foreach($priority as $priority_value){
unset($result1);
foreach($properties as $properties_value){
$result1[] = $priority_value."_".$properties_value;
}
$result[] = $result1;
}
print_r($result);
?>
[/code]
Thanks, mansuang for your post.  I will endeavor to understand / test it.

In the meantime,  I got this working.  Comments / Suggestions are welcome.

I was hung up on trying to use the array() syntax, rather than the $array[][] = syntax... This proved to be
easier for my purposes.  Should there be a more efficient method, I'd love to hear it.

[code]<?php while ( list($cvar,$cval) = each($priority) ) {
    $priority_value = $cval;
while (list($pvar,$pval) = each($properties) ) {
$x[$priority_value][$pval] = $result[$priority_value .'_'.$pval];
}

} ?> [/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.