参数中的字符串到数组 return 数组

string to array return array in parameter

我得到一个类似这样的字符串,"voornaam, achternaam" 我把它赋予一个函数。

当我使用字符串从数据库中获取数据时。

mysql_query("SELECT."$string". FROM ...")

一切顺利。

现在。我想归还我从数据库中选择的值。

我试过类似的方法。

<?php
function user_info($user_id, $fetch = "")
{
if (ctype_digit($user_id))
{
    if (empty($fetch))
    {
        $fetch = "*";
    }
    $query = mysql_query("SELECT ".$fetch." FROM accounts WHERE ID = '".$user_id."'");
    $data = mysql_fetch_assoc($query);
    $data['password'] = NULL;
}

if (empty($fetch))
{
    return $data;
}
else
{
    $fetch = explode(", ", $fetch);
    print_r($fetch);
    while($param = $fetch) {
        return $data[$param];
    }
}

//$item_result['created_by'] gives back a digit
user_info($item_result['created_by'], 'voornaam, achternaam')

我陷入了 while 循环。
我真的不太擅长循环。
所以我尝试了一些东西,对我来说这似乎合乎逻辑。
但在某种程度上它不会起作用。

尝试改变

  while($param = $fetch) {
    return $data[$param];
}

foreach 循环:

$temp = array();
foreach($featch as $key){
  $temp[$key] = (empty($data[$key]) ? ''  :  $data[$key] );
}
return $temp;

更新

或者你可以使用 for 循环 :

$temp = array();
for( $i =0; $i < count($fetch); $i++){
  $temp[$fetch[$i]] = (empty($data[$fetch[$i]]) ? ''  :  $data[$fetch[$i]] );
}
return $temp;

更新 2

或 while 循环

$temp = array();
while(count($fetch)){
  $key = array_shift($fetch);
  $temp[$key] = (empty($data[$key]) ? ''  :  $data[$key] );
}
return $temp;

问题在-

$fetch = explode(", ", $fetch);
print_r($fetch);
while($param = $fetch) {
    return $data[$param];
}

$fetch is an array now and $param is not defined.

你可以试试这个 -

$fetch = explode(", ", $fetch);
$i = 0;
$newData = array();
while($i < count($fetch)) {
    $newData[$fetch] = $data[$fetch];
    $i++;
}
return $newData;

我建议使用 foreach 而不是 while

或者,如果必须在 while 循环中,您可以使用以下内容

$data=array();
while (list($var, $val) = each($fetch)) {
        $data[$var]=$val;
}

正在运行!

我现在拥有的是:

$fetch = explode(", ", $fetch);
    $temp = array();
    for ($i = 0; $i < count($fetch); $i++) {
        $temp[$fetch[$i]] = (empty($data[$fetch[$i]]) ? '' : $data[$fetch[$i]]);
    }
    foreach ($temp as $data) {
        echo $data . ' ';
    }