简体   繁体   English

如何打印从PHP中的函数返回的数组的所有元素?

[英]How to print all elements of array returned from a function in Php?

I have a function that fetches some rows based on the sql query into an array. 我有一个函数,它基于sql查询将某些行提取到数组中。 That array is returned from a function, How can I traverse all the elements of the returned array? 该数组是从函数返回的,我该如何遍历返回数组的所有元素? I am a beginner in Php. 我是Php的初学者。

function get_user_wants($user_id)
{
$query=mysql_query("select product_id from user_wishlist where user_id= $user_id");
return mysql_fetch_assoc($query);
}

$out=get_user_wants($user_id);
print_r($out);

It only prints the first element, or the first record ! 它仅打印第一个元素或第一条记录!

Try something like this: 尝试这样的事情:

$sql = "select product_id from user_wishlist where user_id= $user_id";
$res = mysql_query($sql) or die("FAIL: $sql BECAUSE: " . mysql_error());;
while ($row = mysql_fetch_assoc($res))
{
    print_r($row);
}

And in case you haven't already noticed it, someone will flame you about using MySQL instead of a different thing like MySQLI or PDO. 而且,如果您还没有注意到它,那么有人会激怒您使用MySQL而不是MySQLI或PDO之类的东西。 Don't let them bother you. 不要让他们打扰您。 The point here is that your query returns potentially many rows, and you need some kind of iterator to retrieve all of the rows so your script can process them. 这里的重点是您的查询可能返回许多行,并且您需要某种迭代器来检索所有行,以便脚本可以处理它们。

In the instant case, there will be one product_id element in each $row array. 在这种情况下,每个$ row数组中将有一个product_id元素。 Once you see the output of the print_r() function, it will probably be obvious how you might change the code. 一旦看到print_r()函数的输出,很明显如何更改代码。 This might turn out to be what you want (I think). 这可能是您想要的(我认为)。

function get_user_wants($user_id)
{
    $sql = "select product_id from user_wishlist where user_id= $user_id";
    $res = mysql_query($sql) or die("FAIL: $sql BECAUSE: " . mysql_error());;
    while ($row = mysql_fetch_assoc($res))
    {
        $out[] = $row['product_id'];
    }
    return $out;
}

You are returning the result of a single call to mysql_fetch_assoc() so you will only ever get the first row. 您将返回对mysql_fetch_assoc()的单次调用的结果,因此您将永远只获得第一行。

Loop over them to create a multidimensional array, then return: 循环遍历它们以创建多维数组,然后返回:

function get_user_wants($user_id)
{
    $query=mysql_query("select product_id from user_wishlist where user_id= $user_id");
    $rows = array();
    while($row = mysql_fetch_assoc($query))
    {
         $rows[] = $row;
    }
    return $rows;
}

Now you can loop them with foreach : 现在,您可以使用foreach循环它们:

$list = get_user_wants(99);
foreach($list as $product)
{
    print_r($product);
}

Side note: the mysql_* library is deprecated, it is recommended to upgrade to MySQLi or PDO. mysql_*说明:不建议使用mysql_*库,建议升级到MySQLi或PDO。

You can't. 你不能 The function is only returning the first result. 该函数仅返回第一个结果。 And no more information. 没有更多信息。

So you need to return something different, for example the result resource: 因此,您需要返回不同的内容,例如结果资源:

function get_user_wants($user_id)
{
    $query = mysql_query("select product_id from user_wishlist where user_id= $user_id");

    return $query;
}

You can then iterate over it: 然后,您可以对其进行迭代:

$result = get_user_wants($user_id);

while ($out = mysql_fetch_assoc($result))
{
    print_r($out):
}

A better way then is to wrap the result in an Iterator: 更好的方法是将结果包装在Iterator中:

function get_user_wants($user_id)
{
    $query = mysql_query("select product_id from user_wishlist where user_id= $user_id");

    return new MySqlResult($query);
}

$result = get_user_wants($user_id);

foreach ($result as $out)
{
    print_r($out):
}

Such an result iterator could look like: 这样的结果迭代器可能看起来像:

/**
 * MySql Result Set - Array Based
 */
class MySqlResult implements Iterator, Countable
{
    private $result;
    private $index = 0;
    private $current;

    public function __construct($result)
    {
        $this->result = $result;
    }

    public function fetch($result_type = MYSQL_BOTH)
    {
        $this->current = mysql_fetch_array($this->result, $result_type);
        return $this->current;
    }

    /**
     * Return the current element
     * @link http://php.net/manual/en/iterator.current.php
     * @return array
     */
    public function current()
    {
        return $this->current;
    }

    public function next()
    {
        $this->current && $this->fetch();
    }

    /**
     * Return the key of the current element
     * @link http://php.net/manual/en/iterator.key.php
     * @return mixed scalar on success, or null on failure.
     */
    public function key()
    {
        return $this->current ? $this->index : null;
    }

    /**
     * Checks if current position is valid
     * @link http://php.net/manual/en/iterator.valid.php
     * @return boolean The return value will be casted to boolean and then evaluated.
     * Returns true on success or false on failure.
     */
    public function valid()
    {
        return (bool)$this->current;
    }

    /**
     * Rewind the Iterator to the first element
     * @link http://php.net/manual/en/iterator.rewind.php
     * @return void Any returned value is ignored.
     */
    public function rewind()
    {
        $this->fetch();
    }

    /**
     * Count of rows.
     *
     * @link http://php.net/manual/en/countable.count.php
     * @return int The count of rows as an integer.
     */
    public function count()
    {
        return mysql_num_rows($this->result);
    }
}

Try 尝试

foreach ($out as $key=>$value) 
  echo "$key: $value<br>";

as a starting point. 作为起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM