douxiuyu2028 2013-06-12 01:18
浏览 35
已采纳

比较两个php数组,看看是否与另一个相反[关闭]

So this may be something simple that I am just over looking, but I need to figure out how to do this. This is a question for a class I'm taking, but am not expecting someone to do my work for me ( I'll never learn that way ) I'm more looking for a good starting point. In this example I needed to create an array, sort it, then reverse it. I got that much down.

The final part is to compare the given array with the possibly reversed version and output “True” if it is a correct reversal and output “False” otherwise. It also needs to be done without using the built in php array functions. I'm still new to programming and want to learn. Any help would be much appreciated as I don't even know where to begin with this last part. This is what I have so far.

<?php

//Original array
$the_array = array(5,9,2,8,3,1,7,6,4);
$arrayString = implode(',',$the_array);
echo ("The original array is: ");
echo $arrayString;
echo "<br />";

//Sort loop
// Compares each value in the array to the next one by seeing if the value is greater then the next +1
// If the value is greater then the next value +1 then it stores the value and moves it into the next position.
for ($j = 0; $j < count($the_array); $j++)
{
    for ($i = 0; $i < count($the_array)-1; $i++)
    {
        if ($the_array[$i] > $the_array[$i+1])
        {
            $tmp = $the_array[$i+1];
            $the_array[$i+1] = $the_array[$i];
            $the_array[$i] = $tmp;
        }
    }
}
$arrayString = implode(',',$the_array);
echo ("The array after sorting is: ");
echo $arrayString;
echo "<br />";

//reversal loop
for ($tmp = sizeof($the_array) - 1; $tmp >= 0; $tmp--)
{
    $reverse[] = $the_array[$tmp]; //New reversed array
}
echo ("The reversed array is: ");
$reverseString = implode(',',$reverse);
echo $reverseString;

Any tips in the formatting of my code would also be appreciated.

I actually want to give a thank you to all the responses I got and to the speed of getting them. All the comments and answers have already started to give me a lot of help. I think I may have just been over thinking the problem and some of the things pointed out to me helped me realize this. Thanks again to all.

  • 写回答

4条回答 默认 最新

  • dongrang9300 2013-06-12 01:30
    关注
    • Let A be the first array and B be the second array
    • If length of A == length of B Then
      • For i = 0 To LENGTH(A) - 1
        • If A[i] != B[LENGTH(A) - 1 - i]
          • Return False
      • Return True
    • Else
      • Return False
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 数据量少可以用MK趋势分析吗
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上
  • ¥50 有没有适合匹配类似图中的运动规律的图像处理算法
  • ¥15 dnat基础问题,本机发出,别人返回的包,不能命中