trashcan86 - 10 months ago 43

PHP Question

I'm writing a program in PHP (as it will accompany web code for a mathematics grading system) and I need to create an array of strings and arrays. Specifically, I want to convert something like

`((4)+((5)*(pi)))-((9)*(sqrt(3)))`

to

`[["4", ["5", "pi", "*"], "+"], ["9", ["3", "sqrt"], "*"], "-"]`

which is an array formatting of reverse-polish notation. With this I would evaluate for commutativity accross operators to compare the correct, stored answer to a student's answer. However, I'm unable to do this in PHP with multidimensional arrays due to the unevenness of the rows.

If there's a way to do this using strings, that would be even more helpful (as I plan to store results in an SQL database), but for that I could probably use

`serialize()`

Thanks for any help.

`array()`

`array(array("4", array("5", "pi", "*"), "+"), array("9", array("3", "sqrt"), "*"), "-")`

and serialized notation (for storing in a database) is:

`a:3:{i:0;a:3:{i:0;s:1:"4";i:1;a:3:{i:0;s:1:"5";i:1;s:2:"pi";i:2;s:1:"*";}i:2;s:1:"+";}i:1;a:3:{i:0;s:1:"9";i:1;a:2:{i:0;s:1:"3";i:1;s:4:"sqrt";}i:2;s:1:"*";}i:2;s:1:"-";}.`

Answer

I don't see what's the issue with constructing this array dynamically. For instance, this works (not postfix):

```
$test_array = array(
array(
"4",
array(
"5",
"pi",
"*"
),
"+"
),
array(
"9",
array(
"3",
"sqrt"
),
"*"
),
"-"
);
var_dump($test_array);
```

So making this dynamically using your algorithm should behave in similar manner to doing this (of course the order for adding the element depends on your algorithm):

```
$test_array2 = array();
$test_array2[] = array();
$test_array2[] = array();
$test_array2[] = "-";
$test_array2[1][] = "9";
$test_array2[1][] = array();
$test_array2[1][1][] = "3";
$test_array2[1][1][] = "sqrt";
$test_array2[1][] = "*";
$test_array2[0][] = "4";
$test_array2[0][] = array();
$test_array2[0][1][] = "5";
$test_array2[0][1][] = "pi";
$test_array2[0][1][] = "*";
$test_array2[0][] = "+";
var_dump($test_array2);
```

Both examples above have the same output.