溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

PHP中數組和字符串是如何進行轉換的

發布時間:2021-07-21 10:36:00 來源:億速云 閱讀:167 作者:chen 欄目:編程語言

這篇文章主要介紹“PHP中數組和字符串是如何進行轉換的”,在日常操作中,相信很多人在PHP中數組和字符串是如何進行轉換的問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”PHP中數組和字符串是如何進行轉換的”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

1、數組轉字符串

implode

方法介紹:

function implode ($glue = "", array $pieces) {}

主要有兩個參數

一個是連接符(glue:膠水的意思),默認是空字符串

一個是數組

使用
$test = array("hello","world","php");
echo implode("-",$test);

結果:

hello-world-php

如果是K-V形式的數組呢?

$test = array("h"=>"hello","w"=>"world","p"=>"php");
echo implode("-",$test);

結果還是

hello-world-php

說明還是只對value有作用。

2、字符串分割成數組

2.1 按某個字符分割
function explode ($delimiter, $string, $limit = null) {}

explode (爆炸,可能是把這個字符串炸開?)

參數解釋:

delimiter,分隔符

limit

文檔google翻譯結果:

如果limit設置為正,則返回的數組將包含最大限制元素,最后一個元素包含字符串的其余部分。

個人理解:

limit 限制分割的份數,最后一份為剩下的字符串分割后剩下的,當然如果為1的話,就是字符串本身(已經過實驗)

代碼演示:

$str="hello-world-php";
$result = explode("-", $str);
var_dump($result);
$result = explode("-", $str,2);
var_dump($result);

輸出結果:

array(3) {
  [0]=>
  string(5) "hello"
  [1]=>
  string(5) "world"
  [2]=>
  string(3) "php"
}
array(2) {
  [0]=>
  string(5) "hello"
  [1]=>
  string(9) "world-php"
}
2.2 按距離讀取

可能字符串不用分割,但是需要把每個字符拿出來,也就是一個一個讀出來

原文檔:

**
 * Convert a string to an array
 * @link http://php.net/manual/en/function.str-split.php
 * @param string $string <p>
 * The input string.
 * </p>
 * @param int $split_length [optional] <p>
 * Maximum length of the chunk.
 * </p>
 * @return array If the optional split_length parameter is
 * specified, the returned array will be broken down into chunks with each
 * being split_length in length, otherwise each chunk
 * will be one character in length.
 * </p>
 * <p>
 * false is returned if split_length is less than 1.
 * If the split_length length exceeds the length of
 * string, the entire string is returned as the first
 * (and only) array element.
 * @since 5.0
 */
function str_split ($string, $split_length = 1) {}

部分翻譯:

數組如果指定了可選的split_length參數,則返回的數組將被分解為長度為split_length的塊,否則每個塊將是一個字符長度。

Convert a string to an array,這不就是把字符串轉為數組嘛,用法沒啥可說的

現在我想試一試,如果是5個長度的字符串,按兩位讀取,不足兩位時,最后一位是否保留?

當然推測來說為了數據的完整性,應該是要保留的。

$str = "hello";
var_dump(str_split($str,2));

結果也正如我的推測

array(3) {
  [0]=>
  string(2) "he"
  [1]=>
  string(2) "ll"
  [2]=>
  string(1) "o"
}

到此,關于“PHP中數組和字符串是如何進行轉換的”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

php
AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女