String to array of returned array in parameter

I get a string something like this, "voornaam, achternaam"

I give this to a function.

When I used string to get data from database.

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

everything goes well.

Now. I want to return the values ​​that I have selected from the DB.

I've tried something like this.

<?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')

      

I am stuck with a while loop.
I'm not sure if this is good in loops.
So I tried something and it seems logical to me. But somehow it won't work.

+3


source to share


4 answers


try to change

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

      

in the foreach loop:

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

      


UPDATE



Or you can use for a loop:

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

      


UPDATE 2

OR while loop

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

      

+2


source


Now it works!

Now I have:



$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 . ' ';
    }

      

+2


source


Problem is in

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

      

$fetch

is an array, $param

not defined.

You can try this -

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

      

I would suggest using foreach

instead while

.

+1


source


Alternatively you can use the following if it should be in a while loop

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

      

0


source







All Articles