开发者

how to push data into array in php

开发者 https://www.devze.com 2023-02-25 11:55 出处:网络
Dear All, I want to push the data into array. i am using flowing code. There are two arrays. one holding keys and 2nd values. i am using flowing code

Dear All, I want to push the data into array. i am using flowing code. There are two arrays. one holding keys and 2nd values. i am using flowing code

while($data=mysql_fetch_array($result))
{   
     foreach ($arrTemp as $val) 
    {                   
        array_push($arrKeys, $val);
        array_push($arrValues, $data[$val]);                
    }               
}

print_r($arrKeys);
print_r($arrValues);

$arrReturn = array_combine($arrKeys,$arrValues);

................................... and get flowing results of two arrays.

Array ( [0] => due_date [1] => flag_code [2] => due_date [3] => flag_code [4] => due_date [6] => flag_code  )


Array ( [0] => 12:04:2011 [1] => 0 [2] => 13:04:2011 [3] => 0 [4] => 14:04:2011 [6] => 0  )

when i try to combined the array using array_combined function it only return an array of two values like:开发者_Go百科 Array (due_date => 14:04:2011 flag => 0)

how i can get all values in single array.....!


Its because your have multiple the same array keys. So first it inserts due_date, then flag_code, then it will try and insert another due_date but since this already exists in the array it will overwrite it. Thus the only values left in the array will be the last pair.

The solution is to not have multiple keys that are the same in one array (your due_date and flag_code)

You could do:

foreach ($arrTemp as $val) {                   
    $arrReturn[] = array($val => $data[$val];
}

This will give you each set of results keyed in an array like so:

$arrReturn[0] = array (due_date => 14:04:2011 flag => 0);
$arrReturn[1] = array (due_date => 14:04:2011 flag => 0);
$arrReturn[2] = array (due_date => 14:04:2011 flag => 0);
...


$ctr = 0;
foreach ($arrKeys as $id => $key) {
  $res_array[$ctr][$key] = $arrValues[$id];
  if ($key == 'flag_code') $ctr++;
  }

print_r($res_array);

Output:

Array
(
    [0] => Array
        (
            [due_date] => 12:04:2011
            [flag_code] => 0
        )

    [1] => Array
        (
            [due_date] => 13:04:2011
            [flag_code] => 0
        )

    [2] => Array
        (
            [due_date] => 14:04:2011
            [flag_code] => 0
        )

)
0

精彩评论

暂无评论...
验证码 换一张
取 消