0%

PHP array cheetsheet

PHP array cheetsheet

array_keys: get array keys

array_flip: flip array key and value

array_chunk: split array into chunks

  • split array into chunks (把 array 切成數個小 array)
  • $new_array = array_chunk($input_array, 2)
  • $new_array = array_chunk($input_array, 2, true)
    • true: keep original array key (如果設為 true 表示要保留 array key)
  • useful when data updating in batch (在批次匯入大量資料到 db 的時候好用)
  • Ref: https://www.php.net/manual/en/function.array-chunk.php

array_column: get specific key value from multidimensional array

  • get specific key value from multidimensional array (多層 array,取得每個子層的某個鍵的數值拼成新 array)
  • Get the column of first names from a recordset (取每個子層 key 為 first_name 的值,拼成新 array)
    • $first_names = array_column($records, 'first_name');
  • Get the column of last names from a recordset, indexed by the “id” column (取每個子層 key 為 first_name 的值,並且新 array key 為 id,拼成新 array)
    • $last_names = array_column($records, 'last_name', 'id');
  • Ref: https://www.php.net/manual/en/function.array-column.php

array_combine: creates an array by using one array for keys and another for its values

array_search: find if the value in the array (尋找 array 是否有這個數值,有的話回傳 key)