简体   繁体   English

如何在循环内将关联数组附加到另​​一个数组中-PHP

[英]how to append associative arrays into another array inside loop - php

I really hope you help me with this problem, I hope this make sence for you - I have this pseudo example of foreach loop: 我真的希望您能解决这个问题,希望对您有所帮助-我有foreach循环的伪示例:

foreach_loop {

$k1 = GetKey1(); 
$v1 = GetValue1();

$k2 = GetKey2();
$v2 = GetValue2();

$k3 = GetKey3();
$v2 = GetValue3();

//  now I put those keys and values in associative array called DataArr
 $DataArr[$k1] = $v1;
 $DataArr[$k2] = $v2;
 $DataArr[$k3] = $v3;

}

now my question is, how do I create an array where each index of it contain an associative array created from that foreach loop and keep appending to itself like this: 现在我的问题是,如何创建一个数组,其中每个索引包含一个从该foreach循环创建的关联数组,并像这样继续附加到自身:

     $resultArr = array(
     0 => "DataArr_from_loop1",
     1 => "DataArr_from_loop2",
     2 => "DataArr_from_loop3",
     3 => "DataArr_from_loop4"
     //...etc
     )

and when I check for $resultArr[0] I should get an associative array like this: 当我检查$resultArr[0]我应该得到一个像这样的关联数组:

    array (size=3)
    'k1' => string 'v1'
    'k2' => string 'v2'
    'k3' => string 'v3'

I really need your help, thank you in advance. 我真的需要您的帮助,在此先感谢您。

http://php.net/manual/en/function.array-push.php http://php.net/manual/zh/function.array-push.php

int array_push ( array &$array , mixed $value1 [, mixed $... ] )

or 要么

<?php
/**
* @desc array_push and removes elements from the beginning of the array until it is within limit
* @param    array   Array to push on to
* @param    mixed   Passed to array push as 2nd parameter
* @param    int     Limit (default = 10)
* 
* @return   array   New array
*/
function array_push_limit($array,$add,$limit=10){
    array_push($array, $add);    
    do {        
        array_shift($array);
        $size=count($array);        
    } while($size > $limit);

    return $array;
}
?>
----------
EXAMPLE:
----------
<?php
    $array=array(1, -5, 23, -66, 33, 54, 3);    
    print_r(array_push_limit($array, "HELLO", 4));
?>
----------
OUTPUT:
----------
Array
(
    [0] => 33
    [1] => 54
    [2] => 3
    [3] => HELLO
)

how about... 怎么样...

$resultArr = array();

foreach($whatever as $thing) {

  $k1 = GetKey1(); 
  $v1 = GetValue1();

  $k2 = GetKey2();
  $v2 = GetValue2();

  $k3 = GetKey3();
  $v2 = GetValue3();

  //  now I put those keys and values in associative array called DataArr
  $DataArr = array();  
  $DataArr[$k1] = $v1;
  $DataArr[$k2] = $v2;
  $DataArr[$k3] = $v3;

  $resultArr[] = $DataArr;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM