php 中常用數組操作 數組分割 次數 鍵名差集

來源:互聯網
上載者:User

//

$array=array(1,1,1,1,1,8=>1,4=>1,19,3=>13);    //建立數組
print_r($array);          //輸出數組內容

//

$a=array('green','red','yellow');      //定義第一個數組
$b=array('avocado','apple','banana');     //定義第二個數組
$c=array_combine($a,$b);      //用前兩個數組值作為新數組的鍵與值
print_r($c);         //輸出建立的數組

//
foreach(range(0,12)as $number)     //返回數組0-12
{
  echo $number.",";
}
echo "<p>";
foreach(range(0,100,10)as $number)    //返回數組0,10,20……100
{
  echo $number.",";
}
echo "<p>";
foreach(range('a','i')as $letter)
{
  echo $letter.",";
}
echo "<p>";
foreach(range('c','a')as $letter)      //返回數組c,b,a
{
  echo $letter.",";
}
//
$input_array=array('a','b','c','d','e');     //定義初始數組
print_r(array_chunk($input_array,2));    //將數組分割,不保留原數組鍵名
print_r(array_chunk($input_array,2,true));    //將數組分割,保留原數組鍵名

//
$array=array(1,"hello",1,"php","hello");    //定義一個數組
print_r(array_count_values($array));     //把原數組元素出現次數賦值給新數組並顯示

//

$array1=array("a"=>"green","b"=>"brown","c"=>"blue","red");  //定義數組1
$array2=array("a"=>"green","yellow","red");     //定義數組2
$result=array_diff_assoc($array1,$array2);     //把兩個數組的差集賦值給數組
print_r($result);           //輸出差集的內容

//

$array1=array('blue'=>1,'red'=>2,'green'=>3);     //定義數組1
$array2=array('green'=>4,'blue'=>5,'yellow'=>6);    //定義數組2
$result=var_dump(array_diff_key($array1,$array2));    //對鍵名計算差集
print_r($result); 

//

//定義回呼函數
function key_compare_func($a, $b)
{
  if($a==$b)
  {
    return 0;        //如果兩參數相等,返回0
  }
  return($a>$b)?1:-1;      //如果$a>$b返回1,小於則返回-1
}
//分別定義兩個數組
$array1=array("a"=>"green","b"=>"brown","c"=>"blue","red");
$array2=array("a"=>"green","yellow","red");
//用回呼函數做索引檢查來計算數組的差集
$result=array_diff_uassoc($array1,$array2,"key_compare_func");
print_r($result); 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.