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 求组态王串口自定义通信配置方法或代码?
  • ¥15 实验 :UML2.0 结构建模
  • ¥20 用vivado写数字逻辑实验报告撰写,FPGA实验
  • ¥15 为什么shp文件会有这种小方块?
  • ¥15 ecplise在连接数据库时显示加载驱动成功但是数据库连接失败
  • ¥15 visionmaster启动失败,提示为“机器不满足授权而被禁用”
  • ¥15 IDEA中圈复杂度如何具体设置
  • ¥50 labview采集不了数据
  • ¥15 Multisim红外倒车雷达仿真中距离问题
  • ¥15 请上面代码做什么处理或什么混淆