0

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_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:

     $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:

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

I really need your help, thank you in advance.

1
  • your all three array have same length means same number of element Commented May 5, 2015 at 19:57

2 Answers 2

0

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;

}
Sign up to request clarification or add additional context in comments.

1 Comment

wow man, that worked like magic, I really cant thank you enough, you saved me so much trouble :)
0

http://php.net/manual/en/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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.