1. Solve cross-domain problems

public function __construct()
{
    parent::__construct();
    header('Access-Control-Allow-Origin:*');    / / across domains
}
Copy the code

2, jSON_encode Chinese do not transcode

die( json_encode( $result,JSON_UNESCAPED_UNICODE ) );
Copy the code

3, two-dimensional array sort

$users = array(
    array('name'= >'xiao1'.'age'= >20),
    array('name'= >'xiao2'.'age'= >18),
    array('name'= >'xiao3'.'age'= >22));/* In ascending order by age */
// The age is extracted and stored in a one-dimensional array, then sorted in ascending order by age
$ages= array_column($users.'age');
array_multisort($ages, SORT_ASC, $users);
 
/* First by age, then by name */
$ages= array_column($users.'age');
$names = array_column($users.'name');
array_multisort($ages, SORT_ASC, $names, SORT_DESC, $users);
Copy the code

If PHP. Ini is closed on Linux server, result 406,500. Error information is printed.

ini_set("display_errors"."On");
error_reporting(E_ALL | E_STRICT);
Copy the code

5. Use of list

/ / the list to use
public function test(){
    list($name.$sex) = $this->getInfo();
    echo "Name:{$name}Gender:{$sex}";
}
 
public function getInfo(){
    return ['Joe'.'male'];
}
 
// Output: name: Zhang SAN, gender: male
Copy the code

6. Use of array_column()

$array= [['id'= >'99'.'name'= >'Ninety-nine'],
    ['id'= >'88'.'name'= >'Eighty-eight'],
    ['id'= >'77'.'name'= >'Seventy-seven']];$arr1 = array_column($array.'name');   
// array (0 => '99 ',1 =>' 88 ',2 => '77 ',)
$arr2 = array_column($array.'name'.'id'); 
/ / output: array (99 = > 'ninety-nine', 88 = > 'eighty-eight', 77 = > 'seventy-seven',)
Copy the code
  • Array_column () is used with array_combine()
$ids = array_column($array.'id');
$arrayCombine = array_combine($ids.$array);
/ * $arrayCombine output: Array (99 = > array (' id '= >' 99 ', 'name' = > 'ninety-nine', a), 88 = > array (' id '= >' 88 ', 'name' = > 'eighty-eight',), 77 = > array (' id '= >' 77 ', 'name' = > 'seventy-seven',),) * /
Copy the code

Delete 0,null, index reset

$array = array(0.1.0.2.null.1.3.4.null.0);
$array = array_values(array_unique(array_diff($array[0.null)));/ / remove 0, null; duplicate removal
var_export($array);
 
/ * output: array (0 = > 1, 1 = > 2, 2 = > 3, 3 = > 4,) * /
Copy the code

Convert seconds to minutes

  • Convert seconds to seconds, gmstrftime function, but this function is limited to the conversion of seconds within 24 hours.
$r = gmstrftime('%H:%M:%S', (3600*23) +123);
var_export($r);
// Output: '23:02:03'
Copy the code

9. Interface return

  • The interface returns 1 in normal state and -1 in abnormal state. If the data is empty, it is 1; -1 indicates a parameter exception or logical error.

10, round to keep 2 decimal places.

round($x.2);
Copy the code

11. Hide the middle four digits of your phone number.

$num = "13711111111";
$str = substr_replace($num.'* * * *'.3.4);
Copy the code

12. Newline variable PHP_EOL

Usage scenario: a small line feed, in fact, different platforms have different implementations. The Unix world uses /n instead of newline, but Windows uses /r/n to differentiate itself, and more interestingly, /r on the MAC. PHP_EOL is a variable defined in PHP that represents a line break in PHP. This variable will vary depending on the platform, and will be /r/n on Windows, /n on Linux, and /r on MAC.Copy the code

Isset (), array_key_exists(), empty()

$array = ['a'= >'I was the first.'.'b'= >'I'm the second one'.'c'= >'I'm the third.'.'f'= >null];
if(isset($array['a']) {echo There 'a';
} else {
    echo 'A does not exist';
}

if(array_key_exists('d'.$array)) {
    echo 'd there';
} else {
    echo 'd does not exist ';
}

if (empty($array['f']) {echo 'F does not exist';
} else {
    echo 'f exists and is not null,0,"0",false';
}
 
// A exists d does not exist F does not exist
Copy the code

14, introduce js file, with parameters? _ = 1553829159194

Sometimes the address has an argument like this, right? _ = 1553829159194

  • http://***/index/index?_=1553829159194
  • Add a timestamp after the URL to ensure that the URL changes each time, so that the browser cache is not read.

15. Interface testing tools

  • The interface test tool postman is recommended

16. If the last word is “area”, delete it.

$distName = 'Nanshan';
$lastChar = mb_substr($distName, -1);
if($lastChar= ='area') {$lastChar = mb_substr($distName.0, -1);
}
echo $lastChar;
Copy the code

17. Assume the page content is as follows:

  • The data structure returned from the background:
{"eat": ["Rice"."Wheat"]."drink": ["Water"."Tea"]}
Copy the code
  • Not so good, because you have to have the front end corresponding to the related field, eat, eat; I can’t drink anything.

  • It is best to return:

[{"name":"Eat"."list": ["Rice"."Wheat"] {},"name":"Drink"."list": ["Water"."Tea"]}]
Copy the code

Create directory 0777, mkdir, chmod

  • Creating a folder using mkdir on Windows works fine, but creating a folder using mkdir on Linux does not have the maximum permission 0777. So use the chmod function again, (chmod function for Linux does not have permission to create folders).
// Create a directory if it does not exist
$filePath = '.. /file/20900101';
if(@! file_exists($filePath)){
    mkdir($filePath.0777.true);
    chmod($filePath.0777);
}
Copy the code

19. Reference assignments in foreach

  • code
$temp= [['id'= >1.'name'= >'name1'.'age'= >'age1'.'time'= >'time1' ],
            [ 'id'= >2.'name'= >'name2'.'age'= >'age2'.'time'= >'time2']].Delete the original data
$data = $temp;
foreach ($data as &$value) {$value = [];
}
echo '<pre>';
print_r($data);

Reset the original data
$data = $temp;
foreach ($data as &$value) {$value = [
        'hobby'= >1
    ];
}
print_r($data);

# append original data
$data = $temp;
foreach ($data as &$value) {$value['hobby'] = 1;
}
print_r($data);
Copy the code
  • print
Array([0] = >Array(to)1] = >Array())Array([0] = >Array
        (
            [hobby] => 1
        )

    [1] = >Array
        (
            [hobby] => 1))Array([0] = >Array
        (
            [id] => 1
            [name] => name1
            [age] => age1
            [time] => time1
            [hobby] => 1
        )

    [1] = >Array
        (
            [id] => 2
            [name] => name2
            [age] => age2
            [time] => time2
            [hobby] => 1))Copy the code

20. Url generator

public function test() {
	$url = self::getUrl('http://www.test.com'['id'= >3.'other'= >'good']);
	echo $url . '<br>';     / / print: http://www.test.com?id=3&other=%E5%A5%BD%E7%9A%84
	echo urldecode($url);   // Print: http://www.test.com?id=3&other= ok
}

public function getUrl($apiUrl.$param = []){
    $param = http_build_query($param);
    return $apiUrl . '? ' . $param;
}
Copy the code

Write interface empty array returns object form

  • $dataIs emptyStrong to objectAfter type,json_encodeThe value is{}.If it's not strong, it's==[]==, whether you need to turn to the actual situation
$data = $data ? $data : (object)$data;
Copy the code