用PHP將一個數組存到資料庫的一個欄位的方法

來源:互聯網
上載者:User

要把數一個數組,存到資料庫的一個欄位中,有兩種方法,一種是用序列化函數serialize($arr);還有一種是用php的json擴充內建的函數json_encode($arr);如果json_encode對含有中文的字元進行編碼時,會自動轉換成unicode編碼。就像這樣:a:2:{s:4:”code”;s:1:”1″;s:3:”msg”;s:9:”PHP日誌”;},雖然js上能正常處理,但是看起來還是不那爽,在PHP的官方網站上面找到一個函數,可以解決這個問題,也就是將資料轉換json,而且中文不會被轉換為unicode碼。

 代碼如下 複製代碼
<?php
function php2js($a=false)
{
  if (is_null($a)) return 'null';
  if ($a === false) return 'false';
  if ($a === true) return 'true';
  if (is_scalar($a))
  {
    if (is_float($a))
    {
      // Always use "." for floats.
      $a = str_replace(",", ".", strval($a));
    }

    // All scalars are converted to strings to avoid indeterminism.
    // PHP's "1" and 1 are equal for all PHP operators, but
    // JS's "1" and 1 are not. So if we pass "1" or 1 from the PHP backend,
    // we should get the same result in the JS frontend (string).
    // Character replacements for JSON.
    static $jsonReplaces = array(array("", "/", "n", "t", "r", "b", "f", '"'),
    array('\', '/', 'n', 't', 'r', 'b', 'f', '"'));
    return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
  }
  $isList = true;
  for ($i = 0, reset($a); $i < count($a); $i++, next($a))
  {
    if (key($a) !== $i)
    {
      $isList = false;
      break;
    }
  }
  $result = array();
  if ($isList)
  {
    foreach ($a as $v) $result[] = php2js($v);
    return '[ ' . join(', ', $result) . ' ]';
  }
  else
  {
    foreach ($a as $k => $v) $result[] = php2js($k).': '.php2js($v);
    return '{ ' . join(', ', $result) . ' }';
  }
}
?>





使用方法一:

echo serialize(array(‘code’=>’1′,’msg’=>’PHP日誌’));
輸出:a:2:{s:4:”code”;s:1:”1″;s:3:”msg”;s:9:”PHP日誌”;}

使用方法二:

echo json_encode(array(‘code’=>’1′,’msg’=>’PHP日誌’));
輸出:{“code”:”1″,”msg”:”PHPu65e5u5fd7″}

使用方法三:

echo php2js(array(‘code’=>’1′,’msg’=>’未知錯誤’));
輸出:{ “code”: “1”, “msg”: “PHP日誌” }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.