trashcan86 trashcan86 - 1 year ago 69
PHP Question

PHP array of strings and arrays

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", ["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

Thanks for any help.

EDIT: I think I got it to work. Using the short array notation seemed to cause the problem. The old
notation seems to function properly, like so:

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

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


Answer Source

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

$test_array = 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][] = "+";


Both examples above have the same output.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download