半高级PHP数组

时间:2012-09-29 02:48:45

标签: php arrays

所以我是Arrays的新手,但我认为这应该相当容易,我无法绕过它。

我有一个数组,根据用户输入的数量,它可以有不同数量的键。

$array = MY_Class( array(
   'type' => 'representatives', 
   'show_this_many' => '10'
));

很容易,对吧?

但根据用户输入,我还有1-4个可以在其中的键。他们在第一页填写表格,然后提交到第二页(包含上面的数组)。

根据用户的字段数量,我需要抓住城市第一最后填写在上一页。我不能有空白的

$array = MY_Class( array(
   'type' => 'representatives', 
   'show_this_many' => '10',
   'city' => '',
   'state' => '',
   'first' => $_GET['first']
));

不会真的有用。我需要一种方法来确定哪些字段已经提交(最好通过GET)并以这种方式构建数组。所以最终可以

 $array = MY_Class( array(
   'type' => 'representatives', 
   'show_this_many' => '10',
   'state' => $_GET['state'],
   'first' => $_GET['first']
));

因为第一有一个值,而城市最后没有。

首先想到的是像

$array = MY_Class( array(
   'type' => 'representatives', 
   'show_this_many' => '10',
   $constants => $variables
));

//where
$constants = array( //_GET stuff values );
$variables = array( //_GET stuff with values );

// magic method to make it like
//  CONSTANTS[0] => VARIABLES[0];
//  CONSTANTS[1] => VARIABLES[1];
// so everything is lined up

但我不知道该怎么做:/

2 个答案:

答案 0 :(得分:2)

您将需要使用来自$_GET的可能密钥的白名单,这样您的阵列就不会受到虚假(或可能是恶意)密钥的污染,然后您可以通过循环将它们附加到您的阵列上$_GET

// Your array is already initialized with some values:
$array = array(
  'type' => 'representatives', 
  'show_this_many' => '10' 
);

// Allowed GET keys
$allowed = array('city','state','first');

// Loop over get and add the keys (if allowed)
foreach ($_GET as $key => $value) {
  // If the key is allowed and the value isn't blank...
  if (in_array($allowed, $key) && !empty($value)) {
    $array[$key] = $value;
  }
}

// See all the newly added keys...
var_dump($array);

另一个选择是只将所有键添加到数组中,然后调用array_filter()删除空白。

$array = array(
  'type' => 'representatives', 
  'show_this_many' => '10',
  'city' => '', 
  'state' => '',
  'first' => ''
);
// Add values from $_GET, then filter it
$array = array_filter($array, function($val) {
  return $val !== '' && !is_null($val);
});

答案 1 :(得分:0)

尝试以下代码

$array = array(
  'type' => 'representatives', 
  'show_this_many' => '10'
);

$fields = array ('city', 'state', 'first');

foreach ($fields as $field) {
  if (!empty($_GET[$field])) {
    $array[$field]  = $_GET[$field]
  }
}