简体   繁体   English

PHP字符串和数组数组

[英]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. 我正在用PHP编写程序(因为它将与用于数学评分系统的Web代码一起使用),并且需要创建一个字符串和数组数组。 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. 但是,由于行的不均匀性,我无法在PHP中使用多维数组来做到这一点。

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() . 如果有一种使用字符串的方法,那将更加有用(因为我打算将结果存储在SQL数据库中),但是为此,我可能可以使用serialize()

Thanks for any help. 谢谢你的帮助。

EDIT : I think I got it to work. 编辑 :我想我可以使用它。 Using the short array notation seemed to cause the problem. 使用短数组表示法似乎会引起问题。 The old array() notation seems to function properly, like so: 旧的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:"-";}.

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. 上面的两个示例具有相同的输出。

Here is a function that will do the conversion from string to nested array: 这是一个将字符串转换为嵌套数组的函数:

function convert($string) {
    function nest(&$base) {
        $result = [];
        while (($ch = array_shift($base)) !== null) {
            if ($ch === ')') break;
            $result[] = $ch === '(' ? nest($base) : $ch;
        }
        if (count($result) < 2) return reset($result);
        // Move operator to the end of the array:
        $result[] = array_splice($result, -2, 1)[0];
        return $result;
    }
    // split string into parts, where each bracket is a separate part
    $base = preg_split("/([()])/", $string, 0, PREG_SPLIT_DELIM_CAPTURE 
                                             + PREG_SPLIT_NO_EMPTY);
    // recursively build nested postfix structure
    return nest($base);
}

You would call it like this: 您可以这样称呼它:

$result = convert($string);

For the sample input provided in the question, the output is: 对于问题中提供的样本输入,输出为:

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

Note that the function sqrt is also separated as a postfix function. 请注意,函数sqrt也作为后缀函数分开。

See it run on eval.in . 看到它在eval.in上运行。

For versatility and universality, you could also use an associative array, with, as indexes, their roles, as in one of {operand1, operand2, and operator}. 为了实现通用性和通用性,您还可以使用关联数组,并将其角色用作索引,如{operand1,opernd2和operator}中的一个。 Indeed, any math expression you stated above could be of the pattern: "operand1 operator operand2", however complex they are in the end. 实际上,您上面提到的任何数学表达式都可以采用以下模式:“ operand1运算符operon2”,无论它们到底有多复杂。

Example: 例:

5.pi would be 5.pi将是

array('op1'=>5, 'op'=>'*', 'opd2'=>'pi');

sqrt(3) would be sqrt(3)将是

array('op1' => 3, 'op' => 'sqrt', 'opd2' => null); // since sqrt is a unary function

and so on... 等等...

This way the model would be expandable, you would benefit from the array functions family concerning indexes, without worrying about the orders of the array members, and the parser would be, IMHO, a lot simpler to write, and be read by a human, at least. 这样,模型就可以扩展了,您将从数组函数家族中受益于索引,而不必担心数组成员的顺序,而且解析器,恕我直言,编写起来更容易,并且可以被人阅读,至少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM