Home php教程 PHP源码 php中数值数组、关联数组、多维数组用法

php中数值数组、关联数组、多维数组用法

Jun 08, 2016 pm 05:24 PM
array gt lt nbsp quot

在php中用三种数组分别是数值数组,关联数组,多维数组那么它们三种的用法有一点不同,下面我们来看看吧。

<script>ec(2);</script>

 


数值数组
数值数组存储的每个元素都带有一个数字 ID 键。

可以使用不同的方法来创建数值数组:

例子 1
在这个例子中,会自动分配 ID 键:

 代码如下 复制代码

$names = array("Peter","Quagmire","Joe");

例子 2
在这个例子中,我们人工分配的 ID 键:

 代码如下 复制代码

$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";可以在脚本中使用这些 ID 键:

$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";

echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors";
?>

数组排序

(1)sort(array $array[,int sorttype])
 array 表示一个数组
 

      sorttype 取值:

           SORT_REGULAR - 默认。以它们原来的类型进行处理(不改变类型)。

           SORT_NUMERIC - 把值作为数字来处理

           SORT_STRING - 把值作为字符串来处理

            SORT_LOCALE_STRING - 把值作为字符串来处理,基于本地设置*


 (2)bool rsort(array $array[,sorttype])函数    逆向排序(值逆向)
 sorttype  同上
 (3)bool shuffle()函数    随机排序
 (4)array array_reverse (array $array[,bool preserve_keys])  反向排列
 preserve_keys 为true时 保留原来的键名
 (5)array array_merge()合并数组
 (6)array array_slice(array $array,int offset[,int length[,boolpreserve_keys ])
 offset非负,这array中的偏移变量从此开始,为负时从末端开始
 length为正时,则表示序列中有很多单元,为负时表示从末端开始第几个数处结束,若省略则从offset开始一直到最后
 boolpreserve_keys  同上

数组循环输出

 代码如下 复制代码
<pre class="brush:php;toolbar:false"><br />
<?php<br />
$shuzu=array('a'=>"wo",'b'=>"ni",'c'=>"ta",'d'=>"php",'e'=>"mysql");<br />
echo "使用foreach函数遍历数组";<br />
echo "<br/>$nbsp;<br/>";<br />
foreach($shuzu as $key=>$value)<br />
{<br />
echo "$key 代表: $value";<br />
echo "<br/>$nbsp;<br/>";<br />
}<br />
?><br />
Copy after login

 

关联数组

关联数组,它的每个 ID 键都关联一个值。
在存储有关具体命名的值的数据时,使用数值数组不是最好的做法。
通过关联数组,我们可以把值作为键,并向它们赋值。
例子 1
在本例中,我们使用一个数组把年龄分配给不同的人:

 代码如下 复制代码
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

例子 2
本例与例子 1 相同,不过展示了另一种创建数组的方法:

 代码如下 复制代码

$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";可以在脚本中使用 ID 键:

$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";

echo "Peter is " . $ages['Peter'] . " years old.";
?>以上脚本的输出:
Peter is 32 years old.


关联数组判断为空的代码,然后我们详细讲讲关于数据空的处理。

 代码如下 复制代码
    $array = array(0);
    if(empty($array)){
        echo "我空了n";
    }else{
        echo "我不空啊n";
    }
    $array['array']='我是数组';
    print_r($array);
    $array['array1']='我是数组1';
    print_r($array);
    unset($array['array1']);
    print_r($array);
?>

更多详细内容请查看:http://www.111cn.net/phper/php/39841.htm

遍历

遍历用户列表的时候,只需直接用 isset 查询那个用户名是否存在即可。

PHP 版代码:

 代码如下 复制代码

$arrayHash = array();
foreach($arrayN as $nameN) {
   // 本行执行了 N 次。
   $arrayHash[$nameN] = 1;
}
 

foreach($arrayM as $keyM => $nameM) {
   if (isset($arrayHash[$nameM])) {
   // 本行执行了 M 次!
   unset($arrayM[$keyM]);
   }
}
return $arrayM;
?>

多维

数组

在多维数组中,主数组中的每个元素也是一个数组。在子数组中的每个元素也可以是数组,以此类推。
例子 1
在本例中,我们创建了一个带有自动分配的 ID 键的多维数组:

 代码如下 复制代码
$families = array
(
  "Griffin"=>array
  (
  "Peter",
  "Lois",
  "Megan"
  ),
  "Quagmire"=>array
  (
  "Glenn"
  ),
  "Brown"=>array
  (
  "Cleveland",
  "Loretta",
  "Junior"
  )
);如果输出这个数组的话,应该类似这样:
Array
(
[Griffin] => Array
  (
  [0] => Peter
  [1] => Lois
  [2] => Megan
  )
[Quagmire] => Array
  (
  [0] => Glenn
  )
[Brown] => Array
  (
  [0] => Cleveland
  [1] => Loretta
  [2] => Junior
  )
)

例子 2
让我们试着显示上面的数组中的一个单一的值:

 代码如下 复制代码
echo "Is " . $families['Griffin'][2] .
" a part of the Griffin family?"; 以上代码的输出:
Is Megan a part of the Griffin family?


数组排序

 代码如下 复制代码

$array[] = array("age"=>20,"name"=>"li");
$array[] = array("age"=>21,"name"=>"ai");
$array[] = array("age"=>20,"name"=>"ci");
$array[] = array("age"=>22,"name"=>"di");
 
foreach ($array as $key=>$value){
 $age[$key] = $value['age'];
 $name[$key] = $value['name'];
}
 
array_multisort($age,SORT_NUMERIC,SORT_DESC,$name,SORT_STRING,SORT_ASC,$array);
print_r($array);
?>

更多array_multisort()可参考http://www.111cn.net/phper/php/42696.htm

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution: Your organization requires you to change your PIN Solution: Your organization requires you to change your PIN Oct 04, 2023 pm 05:45 PM

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

How to adjust window border settings on Windows 11: Change color and size How to adjust window border settings on Windows 11: Change color and size Sep 22, 2023 am 11:37 AM

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

How to change title bar color on Windows 11? How to change title bar color on Windows 11? Sep 14, 2023 pm 03:33 PM

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

OOBELANGUAGE Error Problems in Windows 11/10 Repair OOBELANGUAGE Error Problems in Windows 11/10 Repair Jul 16, 2023 pm 03:29 PM

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

How to enable or disable taskbar thumbnail previews on Windows 11 How to enable or disable taskbar thumbnail previews on Windows 11 Sep 15, 2023 pm 03:57 PM

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

Display scaling guide on Windows 11 Display scaling guide on Windows 11 Sep 19, 2023 pm 06:45 PM

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

10 Ways to Adjust Brightness on Windows 11 10 Ways to Adjust Brightness on Windows 11 Dec 18, 2023 pm 02:21 PM

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

See all articles