开发者

Looping through array

I am trying to loop through an array to take certain values and set them equal to a variable.

Here is my var_dump on my $_POST array

array(5) { ["voter"]=> string(2) "22" [1]=> string(1) "1" [2]=> string(1) "2" [3]=> string(1) "3" ["vote"]=> string(4) 

I want the keys ou开发者_如何学运维t of the key => value pair from the 2nd key value pair on out and then set that to a variable. How would I achieve this?

So from [1] -> string(1) "1" on out..Ignore the first pair.

Thanks!


Using the method provided by @Xeon06 will certainly work, but will require the $_POST data to be in the order you provided, and if that order changes, so will the results. This method does not care about the order.

function ext($array, array $keys, $default = NULL)
{
    $found = array();
    foreach ($keys as $key)
    {
        $found[$key] = isset($array[$key]) ? $array[$key] : $default;
    }
    return $found;
}

$keys = array(1, 2, 3, 'vote');
$my_vars = ext($_POST, $keys);

function ext($array, array $keys, $default = NULL) {
    $found = array();
    foreach ($keys as $key) {
        $found[$key] = isset($array[$key]) ? $array[$key] : $default;
    }
    return $found;
}

$_POST = array('voter' => 'TEST', 1 => 'ONE', 2 => 'TWO', 3 => 'THREE', 'vote' => 'HAMBURGER'); 
$keys = array(1, 2, 3, 'vote');
$my_vars = ext($_POST, $keys);
print_r($my_vars);

OUTPUT
Array

(
    [1] => ONE
    [2] => TWO
    [3] => THREE
    [vote] => HAMBURGER
)


I'm not 100% sure of what you're attempting to do, but this will give you an array containing all values but the first.

$vals = array_values(array_slice($_POST, 1));

The array_values part is to reset the indexes of your array, so that accessing $vals with [0] will return "1".


<?php

$str = '';

$arr = array(
    'voter' => '22',
    1 => '1',
    2 => '2',
    3 => '3', 
    'vote' => 'smth',
);

$arr = array_slice($arr, 1);

foreach($arr as $i) {
    $str .= 'id=' . $i . ' ';
}

echo $str; // id=1 id=2 id=3 id=smth

I have no idea how would you use it in a single sql query.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜