根据 php 中的变量,重复获取数组的相同索引值

Get same index value of an array repeated time, based on a variable in php

我们在 PHP 中有一个数组,如下所示:

Array
(
    [0] => Array
        (
            [id] => 29
            [name] => Testing1
        )
    [1] => Array
        (
            [id] => 30
            [name] => Testing2
        )
    [2] => Array
        (
            [id] => 31
            [name] => Testing3
        )
)

我们还有一个变量 $getvalue 。我们想创建一个函数(我们将在 for 循环中使用该函数),我们在其中传递上面的数组和 $getvalue。如果 $getvalue = 2 它应该 return key[0] 2 次,key[1] 2 次和 key[2] 2 次,如下所示。

       [0] => Array
        (
            [id] => 29
            [name] => Testing1
        )
        [0] => Array
        (
            [id] => 29
            [name] => Testing1
        )
        [1] => Array
        (
            [id] => 30
            [name] => Testing2
        )
        [1] => Array
        (
            [id] => 30
            [name] => Testing2
        )
        [2] => Array
        (
            [id] => 31
            [name] => Testing3
        )
        [2] => Array
        (
            [id] => 31
            [name] => Testing3
        )

如果 $getvalue = 1 它应该 return key[0] 1 次,key[1] 1 次和 key[2] 1 次,如下所示。

   [0] => Array
    (
        [id] => 29
        [name] => Testing1
    )
    [1] => Array
    (
        [id] => 30
        [name] => Testing2
    )
   [2] => Array
    (
        [id] => 31
        [name] => Testing3
    )

尝试过:

for($i = 0; $i<=count($array); $i++) {

    foreach($array as $key => $val) {

        if($i==$getvalue )
        {
            $a[] = $array[$i+1];
        }
        else
        {
            $a[] = $array[$i];
        }
      }
    } 

也尝试过:

static function abc ($array,$getvalue)
   {
      foreach ($array as $key => $value) {
        for ($i=0; $i <= $getvalue; $i++) { 
            return $arr[$i];
        }
    }
   }

输入数组的每个元素被添加到 return 值 $getvalue 次:

<?php
function repeatify( array $array, int $getvalue ): array {

    $out = [];
    if($getvalue <= 0) return $out;

    foreach( $array as $element ){
        foreach( range(0, $getvalue - 1) as $we_actualy_are_not_using_this_var )
            $out[] = $element;

        # Or alternatively with a `for` loop (i'll comment this out since i prefer an above code):
        /*
        for (
            $we_actualy_are_not_using_this_var = 0; 
            $we_actualy_are_not_using_this_var < $getvalue; 
            $we_actualy_are_not_using_this_var++
        ) { 
            $out[] = $element;
        }
        */
    }

    return $out;
}


$data = [
    [
        'id' => 29,
        'name' => 'Testing1',
    ],
    [
        'id' => 30,
        'name' => 'Testing2',       
    ],
    [
        'id' => 31,
        'name' => 'Testing2',       
    ],
];

print '<pre>';

print_r( repeatify( $data, 0 ) );
print_r( repeatify( $data, 1 ) );
print_r( repeatify( $data, 2 ) );