Recursive(?) algorithm design help

I have a requirement to allow my end users to input formula much like a spreadsheet. I have an array like this:

\$table = array(
1=>array(
"id"=>1,
"Name"=>"Regulating",
"Quantity"=>"Quantity+Value",
"Value"=>"Cost"
),
...)

The first level array key is always the same value as the id key in that array.

A tabulated example follows: id Name Quantity Value 1 Regulating Quantity+Value Cost 2 Kerbs 3 6 3 Bricks 9 7 4 Sausages Cost 3 5 Bamboo Quantity Cost 6 Clams Quantity NULL 7 Hardcore Quantity*0.5 12 8 Beetles Quantity*Value Value

The Quantity and Value keys represent formula which reference the [id] and either Quantity, Value or Cost.

Cost is derived by multiplying the Value and Quantity.

I am using: preg_match_all("/\[(.*?)\]([A-Z]*[a-z]*)/", \$string, \$matches, PREG_SET_ORDER); which outputs an array like so for[Quantity]:

Array
(
 => Array
(
 => Quantity
 => 2
 => Quantity
)

 => Array
(
 => Value
 => 3
 => Value
)

)

Iterating through the table using something similar to: \$calcString = \$table['Quantity'];

foreach (\$matches as \$match) {
\$calcString = str_replace(\$match, \$table[\$match][\$match], \$calcString);
}

I can get the string to be calculated and am using a matheval class to do the sum.

But here is my issue

I need to resolve references to other parts of the table (which may or may not themselves be formula) to fill in the blanks. This is outside my comfort zone and I would appreciate any advice (or even better functional code) which provides enlightenment on how I might be able to achieve this.

Thanks

• The classic solution is a two-pass compiler. The first builds a table of all references in the program, and the second looks them up from the table. – Davislor Sep 26 '15 at 2:19