user4640949
user4640949

Reputation:

string to array return array in parameter

I get a string something like this, "voornaam, achternaam" I give that to a function.

When I used the string to get the data from the database.

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

this all goes good.

Now. I want to give back the values that I selected from the DB.

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

Im stuck in the while loop.
I am not realy that good in the loops.
So i tried something and to me its seems logical.
But in some way it wont work.

Upvotes: 3

Views: 59

Answers (4)

user4640949
user4640949

Reputation:

It is working now!

What I have now is:

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

Upvotes: 2

Sougata Bose
Sougata Bose

Reputation: 31749

The problem is in -

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

$fetch is an array now and $param is 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 to use foreach instead of while.

Upvotes: 1

Jonny C
Jonny C

Reputation: 1941

Alternatively you could use the following if it HAS to be in a while loop

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

Upvotes: 0

xAqweRx
xAqweRx

Reputation: 1236

try change

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

on foreach loop:

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

UPDATE

Or you can use for 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;

Upvotes: 2

Related Questions