파이썬의 zip과 같은 PHP 함수가 있습니까?
파이썬에는 멋진 zip()
기능이 있습니다. PHP에 상응하는 것이 있습니까?
모든 배열의 길이가 같으면 array_map
with null
를 첫 번째 인수로 사용할 수 있습니다 .
array_map(null, $a, $b, $c, ...);
배열 중 일부가 더 짧은 경우 반환 된 결과가 가장 짧은 배열의 길이 인 파이썬과 달리 가장 긴 길이까지 null로 채워집니다.
array_combine
가까이 온다.
그렇지 않으면 직접 코딩하는 것과 같은 것이 없습니다.
function array_zip($a1, $a2) {
for($i = 0; $i < min(length($a1), length($a2)); $i++) {
$out[$i] = [$a1[$i], $a2[$i]];
}
return $out;
}
이 함수를 사용하여 Python의 배열과 유사한 배열을 만듭니다 zip
.
function zip() {
$args = func_get_args();
$zipped = array();
$n = count($args);
for ($i=0; $i<$n; ++$i) {
reset($args[$i]);
}
while ($n) {
$tmp = array();
for ($i=0; $i<$n; ++$i) {
if (key($args[$i]) === null) {
break 2;
}
$tmp[] = current($args[$i]);
next($args[$i]);
}
$zipped[] = $tmp;
}
return $zipped;
}
이 함수는 원하는만큼 많은 항목과 함께 원하는만큼 많은 배열을 전달할 수 있습니다.
이것은 Python의 zip()
기능 과 똑같이 작동 하며 PHP <5.3 과도 호환됩니다.
function zip() {
$params = func_get_args();
if (count($params) === 1){ // this case could be probably cleaner
// single iterable passed
$result = array();
foreach ($params[0] as $item){
$result[] = array($item);
};
return $result;
};
$result = call_user_func_array('array_map',array_merge(array(null),$params));
$length = min(array_map('count', $params));
return array_slice($result, 0, $length);
};
파이썬이하는 방식으로 배열을 병합하고 zip()
가장 짧은 배열의 끝에 도달 한 후 발견 된 요소를 반환하지 않습니다.
다음과 같은:
zip(array(1,2,3,4,5),array('a','b'));
다음 결과를 제공합니다.
array(array(1,'a'), array(2,'b'))
및 다음 :
zip(array(1,2,3,4,5),array('a','b'),array('x','y','z'));
다음 결과를 제공합니다.
array(array(1,'a','x'), array(2,'b','y'))
위의 증명을 위해이 데모 를 확인하십시오 .
편집 : 단일 인수 수신에 대한 지원이 추가되었습니다 ( array_map
이 경우 다르게 동작 합니다. Josiah에게 감사드립니다 ).
해결책
zip()
매우 밀접하게 일치 하고 동시에 내장 PHP 함수를 사용 하는 솔루션 은 다음과 같습니다.
array_slice(
array_map(null, $a, $b, $c), // zips values
0, // begins selection before first element
min(array_map('count', array($a, $b, $c))) // ends after shortest ends
);
왜 간단한 array_map(null, $a, $b, $c)
전화는 안되나요?
내가로서 이미 내 댓글에 언급 , 나는 호의 nabnabit의 솔루션 (경향 array_map(null, $a, $b, ...)
), 그러나 약간 수정 방법 (위 그림 참조).
일반적으로 다음과 같습니다.
array_map(null, $a, $b, $c);
Python의 대응 요소입니다.
itertools.izip_longest(a, b, c, fillvalue=None)
( list()
반복자 대신 목록을 원하면 감싸십시오 ). 이 때문에 zip()
의 동작 을 모방하기위한 요구 사항에 정확히 맞지 않습니다 (모든 배열의 길이가 같지 않은 경우).
내가 쓴 zip()
내를위한 기능을 열거의 PHP 구현 .
코드는 zip()
Ruby 스타일뿐만 아니라 Python 스타일을 허용하도록 수정되었습니다 . 차이점은 주석에 설명되어 있습니다.
/*
* This is a Python/Ruby style zip()
*
* zip(array $a1, array $a2, ... array $an, [bool $python=true])
*
* The last argument is an optional bool that determines the how the function
* handles when the array arguments are different in length
*
* By default, it does it the Python way, that is, the returned array will
* be truncated to the length of the shortest argument
*
* If set to FALSE, it does it the Ruby way, and NULL values are used to
* fill the undefined entries
*
*/
function zip() {
$args = func_get_args();
$ruby = array_pop($args);
if (is_array($ruby))
$args[] = $ruby;
$counts = array_map('count', $args);
$count = ($ruby) ? min($counts) : max($counts);
$zipped = array();
for ($i = 0; $i < $count; $i++) {
for ($j = 0; $j < count($args); $j++) {
$val = (isset($args[$j][$i])) ? $args[$j][$i] : null;
$zipped[$i][$j] = $val;
}
}
return $zipped;
}
예:
$pythonzip = zip(array(1,2,3), array(4,5), array(6,7,8));
$rubyzip = zip(array(1,2,3), array(4,5), array(6,7,8), false);
echo '<pre>';
print_r($pythonzip);
print_r($rubyzip);
echo '<pre>';
public static function array_zip() {
$result = array();
$args = array_map('array_values',func_get_args());
$min = min(array_map('count',$args));
for($i=0; $i<$min; ++$i) {
$result[$i] = array();
foreach($args as $j=>$arr) {
$result[$i][$j] = $arr[$i];
}
}
return $result;
}
// create
$a = array("a", "c", "e", "g", "h", "i");
$b = array("b", "d", "f");
$zip_array = array();
// get length of the longest array
$count = count(max($a, $b));
// zip arrays
for($n=0;$n<$count;$n++){
if (array_key_exists($n,$a)){
$zip_array[] = $a[$n];
}
if (array_key_exists($n,$b)){
$zip_array[] = $b[$n];
}
}
// test result
echo '<pre>'; print_r($zip_array); echo '<pre>';
비표준 PHP 라이브러리 에서 zip 및 기타 Python 함수를 찾을 수 있습니다 . 연산자 모듈 및 defaultarray 포함 .
use function nspl\a\zip;
$pairs = zip([1, 2, 3], ['a', 'b', 'c']);
function zip() {
$zip = [];
$arrays = func_get_args();
if ($arrays) {
$count = min(array_map('count', $arrays));
for ($i = 0; $i < $count; $i++) {
foreach ($arrays as $array) {
$zip[$i][] = $array[$i];
}
}
}
return $zip;
}
To overcome the issues with passing a single array to map_array
, you can pass this function...unfortunately you can't pass "array"
as it's not a real function but a builtin thingy.
function make_array() { return func_get_args(); }
Dedicated to those that feel like it should be related to array_combine:
function array_zip($a, $b)
{
$b = array_combine(
$a,
$b
);
$a = array_combine(
$a,
$a
);
return array_values(array_merge_recursive($a,$b));
}
you can see array_map
method:
$arr1 = ['get', 'method'];
$arr2 = ['post'];
$ret = array_map(null, $arr1, $arr2);
output:
[['get', 'method'], ['post', null]]
참고URL : https://stackoverflow.com/questions/2815162/is-there-a-php-function-like-pythons-zip
'Development Tip' 카테고리의 다른 글
데이터베이스의 모든 외래 키를 나열 할 수 있습니까? (0) | 2020.12.07 |
---|---|
.NET 용 무료 바코드 API (0) | 2020.12.07 |
파이썬에서 다형성은 어떻게 작동합니까? (0) | 2020.12.07 |
LaTeX에서 기호를 다른 기호 위에 두는 방법은 무엇입니까? (0) | 2020.12.07 |
MSBuild를 통한 MSDeploy에 대한 유효한 매개 변수 (0) | 2020.12.07 |