刪除數組與二維數組值的php代碼
Jun 13, 2016 am 09:55 AM方法如下:
$arr = array(…………) ;//假設有一萬個元素的數組,里面有重復的元素。
$arr = array_flip(array_flip($arr)); //這樣便可以刪除重復元素。
究竟是怎么回事呢?來看下array_flip()的作用:array_flip()用于將一個數組的每個元素的鍵和值交換,如:
$arr1 = array (”age” => 30, “name” => “快樂園”);
$arr2 = array_flip($arr1); //$arr2 就是 array(30 => “age”, “快樂園” => “name”);
在PHP的數組中,允許不同的元素可以取同一個值,但不允許同一個鍵名被不同的元素使用,如:
$arr1 = array (”age” => 30, “name” => “快樂園”, “age” => 20); “age” => 20將會取代”age” => 30
$arr1 = array (”name” => “快樂園”, “age” => 45);
這里 $arr1與$arr2 是相等的。
于是,我們便可以知道,為什么 array_flip(array_flip($arr)) 可以刪除數組中重復的元素了。首先,$arr里的值會變成鍵名,因為值是有重復的,變成鍵名之后這些重復的值便成了重復的鍵名,PHP引擎將重復的鍵名刪除,只保留最后一個。如:
$arr1 = array (”age” => 30, “name” => “快樂園”, “age” => 20);
$arr1 = array_flip($arr1); //$arr1 變成了 array(”快樂園” => “name”, 20 => “age”);
//再把 $arr1 的鍵名與值還復:
$arr1 = array_flip($arr1);
上面的代碼寫得簡潔一些就是: $arr1 = array_flip(array_flip($arr1));
?
上面寫了一篇關于數組去重的文章,但是僅限于一維數組。下面的函數可以用于二維數組:
復制代碼 代碼如下:
//二維數組去掉重復值
function array_unique_fb($array2D)
{
foreach ($array2D as $v)
{
$v = join(",",$v); //降維,也可以用implode,將一維數組轉換為用逗號連接的字符串
$temp[] = $v;
}
$temp = array_unique($temp); //去掉重復的字符串,也就是重復的一維數組
foreach ($temp as $k => $v)
{
$temp[$k] = explode(",",$v); //再將拆開的數組重新組裝
}
return $temp;
}
如果你想保留數組的鍵值,可以用下面的函數:
復制代碼 代碼如下:
//二維數組去掉重復值 并保留鍵值
function array_unique_fb($array2D)
{
foreach ($array2D as $k=>$v)
{
$v = join(",",$v); //降維,也可以用implode,將一維數組轉換為用逗號連接的字符串
$temp[$k] = $v;
}
$temp = array_unique($temp); //去掉重復的字符串,也就是重復的一維數組
foreach ($temp as $k => $v)
{
$array=explode(",",$v); //再將拆開的數組重新組裝
$temp2[$k]["id"] =$array[0];
$temp2[$k]["litpic"] =$array[1];
$temp2[$k]["title"] =$array[2];
$temp2[$k]["address"] =$array[3];
$temp2[$k]["starttime"] =$array[4];
$temp2[$k]["endtime"] =$array[5];
$temp2[$k]["classid"] =$array[6];
$temp2[$k]["ename"] =$array[7];
}
return $temp2;
}
大概就這樣啦。
二維數組去重
復制代碼 代碼如下:
$arr = array(
array('id' => 1,'name' => 'aaa'),
array('id' => 2,'name' => 'bbb'),
array('id' => 3,'name' => 'ccc'),
array('id' => 4,'name' => 'ddd'),
array('id' => 5,'name' => 'ccc'),
array('id' => 6,'name' => 'aaa'),
array('id' => 7,'name' => 'bbb'),
);
function assoc_unique(&$arr, $key)
{
$rAr=array();
for($i=0;$i{
if(!isset($rAr[$arr[$i][$key]]))
{
$rAr[$arr[$i][$key]]=$arr[$i];
}
}
$arr=array_values($rAr);
}
assoc_unique(&$arr,'name');
print_r($arr);
?>
利用php自帶函數
說明
array array_unique ( array $array )
array_unique() 接受 array 作為輸入并返回沒有重復值的新數組。
注意鍵名保留不變。array_unique() 先將值作為字符串排序,然后對每個值只保留第一個遇到的鍵名,接著忽略所有后面的鍵名。這并不意味著在未排序的 array 中同一個值的第一個出現的鍵名會被保留。
?
Note: 當且僅當 (string) $elem1 === (string) $elem2 時兩個單元被認為相同。就是說,當字符串的表達一樣時。第一個單元將被保留。
Example #1 array_unique() 例子
?
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
上例將輸出:Array
(
??? [a] => green
??? [0] => red
??? [1] => blue
)
Example #2 array_unique() 和類型$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
?>
上例將輸出:array(2) {
? [0] => int(4)
? [2] => string(1) "3"
}
相關教程
http://www.bKjia.c0m/phper/php-function/34794.htm

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

In JavaScript, check whether an array contains a certain value. The most common method is include(), which returns a boolean value and the syntax is array.includes(valueToFind), for example fruits.includes('banana') returns true; if it needs to be compatible with the old environment, use indexOf(), such as numbers.indexOf(20)!==-1 returns true; for objects or complex data, some() method should be used for in-depth comparison, such as users.some(user=>user.id===1) returns true.

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses
