简体   繁体   English

正确的从C#到PHP的转换功能

[英]Correct conversion function from C# to PHP

there is a function in C# (the main task of the function with an example ) : C#中有一个函数(该函数的主要任务带有示例

Int32[] Spiral_Min(Int32[, ] arr) {
    List <Int32> list = new List <Int32> ();
    Int32 n = arr.GetLength(0);
    Int32 count = n;
    Int32 value = -n;
    Int32 sum = -1;
    do {
        value = -1 * value / n;
        for (Int32 i = 0; i < count; i++) {
            sum += value;
            list.Add(arr[sum / n, sum % n]);
        }
        value *= n;
        count--;
        for (Int32 i = 0; i < count; i++) {
            sum += value;
            list.Add(arr[sum / n, sum % n]);
        }
    } while (count > 0);
    return list.ToArray();
}

I'm trying to do the same in PHP, but i ran into a problem in the code, there is a string: 我试图在PHP中做同样的事情,但是我在代码中遇到了一个问题,有一个字符串:

arr[sum / n, sum % n]

I do not understand how to do this in PHP, tried it through array_merge , but the function still doesn't work. 我不明白如何在PHP中执行此操作,但通过array_merge尝试了该功能,但该功能仍然无法正常工作。

function f($a)
{
    $n = count($a[0]);
    $count = $n;
    $value = -$n;
    $sum = -1;

    do
    {
        $value = -1 * $value / $n;

        for ($i = 0; $i < $count; $i++) {
            $sum += $value;
            $r[] = array_merge($a[$sum / $n], $a[$sum % $n]);
        }

        $value *= $n;
        $count--;

        for ($i = 0; $i < $count; $i++) {
            $sum += $value;
            $r[] = array_merge($a[$sum / $n], $a[$sum % $n]);
        }
    }
    while ($count > 0);

    return $r;
}

Please tell me what the problem is and how to do it right? 请告诉我问题出在哪里以及如何正确解决?

Assuming $arr is a two dimensional array, you can access elements from the arrays using $arr[$index1][$index2] notation. 假设$arr是一个二维数组,则可以使用$arr[$index1][$index2]表示法访问数组中的元素。 Thus: 从而:

arr[sum / n, sum % n]

Would become: 会成为:

$arr[$sum / $n][$sum % $n]

You can use array_push. 您可以使用array_push。 Like below: 如下所示:

function f($a)
{
    $n = count($a);
    $count = $n;
    $value = -$n;
    $sum = -1;
    $r = [];
    do
    {
        $value = -1 * $value / $n;
        for ($i = 0; $i < $count; $i++) {
            $sum += $value;
            array_push($r, $a[$sum / $n], $a[$sum % $n]);
        }
        $value *= $n;
        $count--;

        for ($i = 0; $i < $count; $i++) {
            $sum += $value;
            array_push($r, $a[$sum / $n], $a[$sum % $n]);
        }
    }
    while ($count > 0);
    return $r;
}

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

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