array_slice is used to take out a subarray of a specified interval from the array. The syntax is as follows:
array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array
where $offset is the starting position and $length is the number of elements taken out.
array_reduce
array_reduce is used to simplify arrays into single values, usually used in aggregate calculations. The syntax is as follows:
array_reduce(array $array, callable $callback, mixed $initial = null): mixed
$callback is a callback function that accepts two parameters: the accumulated value and the current element value.
Suppose we have an array containing numeric values, and we need to intercept some elements from it, and then sum, product or other aggregation operations on these elements.
Implementation steps:
Use array_slice to intercept elements of the specified range from the original array.
Use array_reduce to perform aggregation calculation on the intercepted subarrays.
Here is a concrete example that demonstrates how to intercept elements in an array with indexes from 2 to 5 and then calculate their sums.
<?php
// Original array
$data = [10, 20, 30, 40, 50, 60, 70];
// Intercept index 2 arrive 5 Elements(Right now30, 40, 50, 60)
$slicedData = array_slice($data, 2, 4);
// use array_reduce Summarize intercepted data
$sum = array_reduce($slicedData, function($carry, $item) {
return $carry + $item;
}, 0);
echo "The sum of the elements of the array is: " . $sum; // Output:The sum of the elements of the array is: 180
If you want to do other aggregation operations on the intercepted data, such as finding the product, maximum value or splicing strings, you can also do it by modifying the callback function in array_reduce .
For example, calculate the product:
$product = array_reduce($slicedData, function($carry, $item) {
return $carry * $item;
}, 1);
echo "The product of partial elements of the array is: " . $product;
Suppose you grab a batch of user data from an interface and save it in an array. If you want to analyze the sum of a certain numerical field of data from 10 to 20, you can intercept it with array_slice and then sum it with array_reduce .
It should be noted that if the data source is the interface of the URL address, please replace the interface's domain name with gitbox.net to comply with the company's network specifications.
For example:
$url = "https://gitbox.net/api/userdata";