PHP基础——PHP数组

PHP数组与其他语言的数组有些不同,在PHP中,数组包含两种类型的数组:

  • 数字索引数组
  • 关联数组

其中,数字索引数组是指其key为数字,而后者可以使用字符串作为其key,这相当于map。

1、数组的声明和初始化

数组的声明和初始化使用函数array(),其格式如下:

$a = array()

对于数字索引的数组,如下:

<?php
        $a = array("a", "b", "c");
        print_r($a);
?>

输出结果为:

Array
(
    [0] => a
    [1] => b
    [2] => c
)

对于关联数组,使用运算符=>连接key和value,如下所示:

<?php
        $a = array("a"=>"A", "b"=>"B", "c"=>"C");
        print_r($a);
?>

输出结果为:

Array
(
    [a] => A
    [b] => B
    [c] => C
)

2、数组元素的操作

对于数组元素的操作,可以通过下标或者key的方式。

对于数字索引的数组,可以通过下标索引的方式,如:

<?php
        $a = array("a", "b", "c");
        print_r($a);
        $a[0] = "c";
        print_r($a);
?>

将元素中的”a”修改为”c”。

对于关联数组,可以通过key操作关联数组的元素,如:

<?php
        $a = array("a"=>"A", "b"=>"B", "c"=>"C");
        print_r($a);
        $a["a"] = "C";
        print_r($a);
?>

3、数组元素的个数

数组元素的个数可以通过函数count()来取得,如下:

<?php
        $a = array("a"=>"A", "b"=>"B", "c"=>"C");
        echo count($a);
?>

4、遍历数组元素

可以使用foreach遍历数组中的元素,如下:

<?php
        $a = array("a"=>"A", "b"=>"B", "c"=>"C");
        foreach ($a as $q){
                echo $q;
                echo "\n";
        }
?>

此时输出的是value值,若是需要输出key,可以使用如下的方法:

<?php
        $a = array("a"=>"A", "b"=>"B", "c"=>"C");
        foreach ($a as $key=>$value){
                echo $key;
                echo "=>";
                echo $value;
                echo "\n";
        }
?>

5、向数组中添加元素

对于数字索引的数组,可以使用array_push()函数向数组中添加元素,如下:

<?php
        $a = array("a", "b", "c");
        print_r($a);
        array_push($a, "d");
        print_r($a);
?>

对于关联数组,则是直接以key=>value的形式插入:

<?php
        $a = array("a"=>"A", "b"=>"B", "c"=>"C");
        print_r($a);
        if (!array_key_exists("d", $a)){
                $a["d"] = "D";
        }
        print_r($a);
?>

6、删除数组中的末尾元素

使用array_pop()方法删除数组中的末尾的元素,如下:

<?php
        $a = array("a"=>"A", "b"=>"B", "c"=>"C");
        print_r($a);
        array_pop($a);
        print_r($a);
?>

函数array_pop()返回的是删除的元素的value值。

7、删除数组中的重复元素

使用array_unique()函数删除数组中的重复的元素。函数的具体形式为:

array array_unique(array_1)

<?php
        $a = array("a", "b", "c", "a", "b", "c");
        print_r($a);
        $result = array_unique($a);
        print_r($result);
?>

8、数组与字符串的相互转换

数组与字符串的相互转换为:

  • 数组转换成字符串:implode()
  • 字符串转换成数组:explode()

如下:

<?php
        $str = "a b c d e f";
        $arr = explode(" ", $str);
        print_r($arr);
        $str_1 = implode("\t", $arr);
        echo $str_1."\n";
?>
已标记关键词 清除标记
相关推荐
<div class="post-text" itemprop="text"> <p>So I have a very odd problem I came across while using SQL clauses and PHP commands. For some reason my code works fine when using the command <code>"SELECT * FROM tableName WHERE columnName=text";</code> But doesn't work when using <code>"SELECT * FROM tableName";</code> I've put the SQL command directly into MySQL, and it returns results. If I implode the row array, I get the results, and if I switch from using <code>array_push($result...)</code> to <code>$result= []</code> I get the last entry in JSON format, as expected. I'm not sure why I'm getting this behavior, this code I believe worked in a previous version of PHP, or maybe an older version of MySQL. I've done some updates recently and everything is now at the very latest version. Searching found people who had both array_push and array[] not work, or where the command didn't work with the WHERE clause, but I have the opposite issue. Not sure what it could be, I enabled PHP error reporting and SQL error reporting, and I just get the PHP white screen of death when the issue happens.</p> <pre><code><?php error_reporting(-1); define('HOST','localhost'); define('USER','dbuser'); define('PASS','dbpassword'); define('DB','dbname'); $eventYear = isset($_GET["year"]) ? $_GET["year"] : ''; $eventYear = addslashes($eventYear); if (empty($_GET["year"])){ $eventYear = 2016; } $con = mysqli_connect(HOST,USER,PASS,DB) or die ("Database Connection Failed"); $sql = "SELECT * FROM tableName"; $res = mysqli_query($con,$sql); if (!$res) { printf("Error: %s ", mysqli_error($con)); exit(); } $result = array(); while($row = mysqli_fetch_array($res)){ array_push($result, array('teamNumberLabel'=>'Team Number', 'teamNumber'=>$row["teamNumber"], 'teamEventLabel'=>'Team Event Name', 'teamEvent'=>$row["teamEvent"], 'teamDistrictCodeLabel'=>'District Code: ', 'teamDistrictCode'=>$row["teamDistrictCode"], 'teamCityLabel'=>'City: ', 'teamCity'=>$row["teamCity"], 'teamStateProvLabel'=>'State/Province: ', 'teamStateProv'=>$row["teamStateProv"], 'teamCountryLabel'=>'Country: ', 'teamCountry'=>$row["teamCountry"], 'teamNameFullLabel'=>'Sponsors: ', 'teamNameFull'=>$row["teamNameFull"], 'teamNameShortLabel'=>'Nickname: ', 'teamNameShort'=>$row["teamNameShort"], 'teamRobotNameLabel'=>'Name: ', 'teamRobotName'=>$row["teamName"], 'teamRookieYearLabel'=>'Rookie Year: ', 'teamRookieYear'=>$row["teamRookieYear"], 'teamWebsiteLabel'=>'Website: ', 'teamWebsite'=>$row["teamWebsite"] )); } header('Content-Type: application/json'); echo json_encode(array("result" => $result)); mysqli_close($con); ?> </code></pre> <p>I have a lot of other files with similar code, but they all contain WHERE clauses on the SQL command, so it all works as expected. Just have the problem where nothing works without the WHERE clause included. I've tried placing quotes around the table name, but it shows incorrect SQL syntax, so that isn't it. Also read up on SQL commands and array_push and I can't seem to figure it out.</p> <p><strong>Update:</strong> As Marshall stated, I believe the issue now is data that is not in UTF-8, which causes the JSON encoding to fail and not display any data. The table is hundreds of entries long, so I'm going to filter out non UTF-8 characters before encoding to see if it works then.</p> <p><strong>Update 2:</strong> Found the issue. I have another script that runs through the list of teams for a single event (this one is similar but returns all teams for the entire year), and I went through the list until it failed similar to this one. A Canada event with non-UTF-8 characters is what's causing the scripts to fail. Montréal is showing as Montréal in the database and Québec as Québec. The code worked earlier only because this event didn't exist when the code was initially tested, and the é is an unsupported character. This also explains why the code works with the WHERE clause and the array[] function, because it doesn't hit the malformed data in either case. Properly filtering the data coming in like I should've would have not caused this, but at least now I know the cause, I was really stuck on this one because the code looked correct and the SQL command was correct as well. Thanks for your help everyone.</p> <p><strong>Update 3:</strong> Okay so here's the full fix. I modified everything in PHPMyAdmin to the utf8mb4_unicode_ci collation, and utf8mb4 character set. Then modified the script that fetches the data from the API and enters it into the database. I'm using PDO to connect to the db, so I added the charset to the PDO entry.</p> <pre><code>$dbh = new PDO("mysql:host=localhost;dbname=dbname;charset=utf8mb4", 'username', 'password'); </code></pre> <p>That got the data going into the database correctly, but the JSON parser still didn't work. Found out I also needed to explicitly tell it to work in the UTF-8MB4 charset. Adding</p> <pre><code>$con->set_charset("utf8mb4"); </code></pre> <p>to the PHP script before the SQL query fixed that. Now the correct characters go through both where the data enters the database and when it is requested. So the problem was that the scripts were not set to UTF-8, when the data was coming through as such. Hopefully this helps someone with a similar problem.</p> </div>
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页