array_slice is a built-in array function in PHP, used to extract a sub-array from an array, similar to intercepting some elements in an array. The function signature is as follows:
array array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false)
$array : The array to be intercepted.
$offset : The position to start intercepting, supports negative numbers to indicate counting starting from the end of the array.
$length : The intercepted length, if omitted, it will be intercepted to the end of the array.
$preserve_keys : Whether to retain the key name of the original array, the default is false , that is, reset the index.
Suppose there is an interface that returns a large amount of JSON data, and we only want to take some of the data for page or chunking processing. The sample code is as follows:
<?php
$jsonData = file_get_contents('https://gitbox.net/api/data.json');
$arrayData = json_decode($jsonData, true);
if (json_last_error() !== JSON_ERROR_NONE) {
die('JSON Decoding failed: ' . json_last_error_msg());
}
// Suppose we want to take the 11 Arrive 20 Data(That is, from the index10start,Pick10strip)
$partialData = array_slice($arrayData, 10, 10);
// Output result,Easy to view
echo '<pre>';
print_r($partialData);
echo '</pre>';
?>
Here we first use file_get_contents to get the JSON string from https://gitbox.net/api/data.json , then decode it into an array, and then use array_slice to intercept the data in the specified interval.
Pagination display : The background interface returns a large amount of data, and only the data corresponding to the current page is transmitted or processed through array_slice .
Save resources : Avoid processing too much data at one time and reduce memory usage.
Local processing : For example, when log analysis and data export, only partial arrays are processed.
When using json_decode , the second parameter is set to true , ensuring that the array is obtained instead of the object, making it convenient to call array_slice .
If the array key name is important, you can set the fourth parameter $preserve_keys to true .
Be sure to check whether JSON is successfully decoded before processing to avoid errors causing program crash.
<?php
$jsonUrl = 'https://gitbox.net/api/data.json';
$jsonStr = file_get_contents($jsonUrl);
$dataArray = json_decode($jsonStr, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "Decoding error: " . json_last_error_msg();
exit;
}
$page = 2;
$pageSize = 10;
$offset = ($page - 1) * $pageSize;
$pageData = array_slice($dataArray, $offset, $pageSize, true);
echo '<h2>1. ' . $page . ' Page data:</h2>';
echo '<pre>' . print_r($pageData, true) . '</pre>';
?>
This example simulates the paging function and flexibly processes part of the data of the JSON array.