jjzjj

php - print_r() 函数返回 diff 算法的简单结果 "Array"

coder 2023-10-25 原文

我使用的是 diff 算法 ( the Paul Butler one ),现在我开始使用它了。我发现我需要 mysql_fetch_array() 而不是 mysql_fetch_object(),它解决了警告和错误消息,但现在当我尝试 print_r() 显示结果时,结果只是“Array”而不是数据库中的字段我需要它来显示和比较...当我调用不同的函数时,它似乎显示了字段,但不比较它们而不是将它们列出两次并使用 Array ( [0] => Array ( [ d] => 数组 ( [0] => 在它之前。

知道为什么吗?是的,我用谷歌搜索并查找了它,并花了大约两天时间试图解决这个问题。

这是脚本的一部分:

    $oldhistory = mysql_query("SELECT history FROM members WHERE id = '$id'") or die(mysql_error());
    $oldhistory = mysql_fetch_array($oldhistory);

    $newhistory = mysql_query("SELECT history FROM profile_edit WHERE userid = '$id'") or die(mysql_error());   
    $newhistory = mysql_fetch_array($newhistory);

    $oldpersonality= mysql_query("SELECT personality FROM members WHERE id = '$id'") or die(mysql_error());
    $oldpersonality = mysql_fetch_array($oldpersonality);

    $newpersonality = mysql_query("SELECT personality FROM profile_edit WHERE userid = '$id'") or die(mysql_error());   
    $newpersonality = mysql_fetch_array($newpersonality);

    $oldappearance = mysql_query("SELECT description FROM members WHERE id = '$id'") or die(mysql_error());
    $oldappearance = mysql_fetch_array($oldappearance);

    $newappearance = mysql_query("SELECT personality FROM profile_edit WHERE userid = '$id'") or die(mysql_error());    
    $newappearance = mysql_fetch_array($newappearance);

    echo "
      <form action=\"$PHP_SELF?id=$id&s=a\" method=\"post\">
      <table cellpadding=\"5\" cellspacing=\"1\" border=\"0\" align=\"center\" bgcolor=\"#234904\">
        <tr bgcolor=\"#000000\">
         <td>History :: </td>
         <td> 
";

function diffhistory($oldhistory, $newhistory){

foreach($oldhistory as $oindex => $ovalue){
        $nkeys = array_keys($newhistory, $ovalue);
        foreach($nkeys as $nindex){
            $matrix[$oindex][$nindex] = isset($matrix[$oindex - 1][$nindex - 1]) ?
                $matrix[$oindex - 1][$nindex - 1] + 1 : 1;
            if($matrix[$oindex][$nindex] > $maxlen){
                $maxlen = $matrix[$oindex][$nindex];
                $omax = $oindex + 1 - $maxlen;
                $nmax = $nindex + 1 - $maxlen;
            }
        }   
    }
    if($maxlen == 0) return array(array('d'=>$oldhistory, 'i'=>$newhistory));
    return array_merge(
        diffhistory(array_slice($oldhistory, 0, $omax), array_slice($newhistory, 0, $nmax)),
        array_slice($newhistory, $nmax, $maxlen),
        diffhistory(array_slice($oldhistory, $omax + $maxlen), array_slice($newhistory, $nmax + $maxlen)));
}

function htmlDiffHistory($oldhistory, $newhistory){
    $diffhistory = diffhistory(explode(' ', $oldhistory), explode(' ', $newhistory));
    foreach($diffhistory as $k){
        if(is_array($k))
            $ret .= (!empty($k['d'])?"<del><color=red>".implode(' ',$k['d'])."</color></del> ":'').
                (!empty($k['i'])?"<ins><color=green>".implode(' ',$k['i'])."</color></ins> ":'');
        else $ret .= $k . ' ';
    }
    return $ret;

}
print_r (diffhistory($oldhistory, $newhistory));

最佳答案

可能您只需要使用 mysql_fetch_assoc()(或者可能是 mysql_fetch_row())从数据库读取数据作为关联或索引,而不是两者兼而有之,但我怀疑您的方法存在很大缺陷-一方面,您要在一个地方进行 6 个查询。您还将一个单值数组传递给一个函数,我怀疑该函数需要两个多值数组进行比较。

试试这个(根据下面的评论编辑):

<?php

  function diff($old, $new){
    $maxlen = 0;
    foreach ($old as $oindex => $ovalue) {
      $nkeys = array_keys($new, $ovalue);
      foreach ($nkeys as $nindex) {
        $matrix[$oindex][$nindex] = isset($matrix[$oindex - 1][$nindex - 1])
          ? $matrix[$oindex - 1][$nindex - 1] + 1
          : 1;
        if ($matrix[$oindex][$nindex] > $maxlen) {
          $maxlen = $matrix[$oindex][$nindex];
          $omax = $oindex + 1 - $maxlen;
          $nmax = $nindex + 1 - $maxlen;
        }
      } 
    }
    return ($maxlen == 0)
      ? array(array('d'=>$old, 'i'=>$new))
      : array_merge(
          diff(array_slice($old, 0, $omax), array_slice($new, 0, $nmax)),
          array_slice($new, $nmax, $maxlen),
          diff(array_slice($old, $omax + $maxlen), array_slice($new, $nmax + $maxlen)));
  }

  function htmlDiff($old, $new){
    $ret = '';
    $diff = diff(preg_split('/\s+/', $old), preg_split('/\s+/', $new));
    foreach ($diff as $k) {
      if (is_array($k)) {
          $ret .= (!empty($k['d']) ? "<del style='color:red'>".implode(' ',$k['d'])."</del> " : '')
                . (!empty($k['i']) ? "<ins style='color:green'>".implode(' ',$k['i'])."</ins> " : '');
      } else {
        $ret .= $k . ' ';
      }
    }
    return $ret;
  }

  $query = "
    SELECT
      `m`.`history`, `p`.`history` AS 'p_history',
      `m`.`personality`, `p`.`personality` AS 'p_personality',
      `m`.`description`, `p`.`description` AS 'p_description'
    FROM `members` `m`
    JOIN `profile_edit` `p` ON `p`.`userid` = `m`.`id`
    WHERE `m`.`id` = '".mysql_real_escape_string($id)."'
    LIMIT 1
  ";

  $result = mysql_query($query) or die(mysql_error());
  $data = mysql_fetch_assoc($result);

  echo "
    <form action=\"$PHP_SELF?id=$id&s=a\" method=\"post\">
      <table cellpadding=\"5\" cellspacing=\"1\" border=\"0\" align=\"center\" bgcolor=\"#234904\">
        <tr bgcolor=\"#000000\">
          <td>History :: </td>
          <td>".htmlDiff(htmlspecialchars($data['history']), htmlspecialchars($data['p_history']))."</td>
        </tr>
        <tr bgcolor=\"#000000\">
          <td>Personality :: </td>
          <td>".htmlDiff(htmlspecialchars($data['personality']), htmlspecialchars($data['p_personality']))."</td>
        </tr>
        <tr bgcolor=\"#000000\">
          <td>Description :: </td>
          <td>".htmlDiff(htmlspecialchars($data['description']), htmlspecialchars($data['p_description']))."</td>
        </tr>
      </table>
    </form>";

关于php - print_r() 函数返回 diff 算法的简单结果 "Array",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9196178/

有关php - print_r() 函数返回 diff 算法的简单结果 "Array"的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby - 在 Ruby 中实现 `call_user_func_array` - 2

    我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)

  4. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  5. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  6. Ruby Koans about_array_assignment - 非平行与平行分配歧视 - 2

    通过ruby​​koans.com,我在about_array_assignment.rb中遇到了这两段代码你怎么知道第一个是非并行赋值,第二个是一个变量的并行赋值?在我看来,除了命名差异之外,代码几乎完全相同。4deftest_non_parallel_assignment5names=["John","Smith"]6assert_equal["John","Smith"],names7end45deftest_parallel_assignment_with_one_variable46first_name,=["John","Smith"]47assert_equal'John

  7. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  8. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  9. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  10. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

随机推荐