0

I am passing an associative array(positions) via render:

 render("portfolio.php", [ "title" => "Portfolio","positions" => $positions]);

and trying to print it in portfolio using below code:

 foreach ($positions as $position)
    {
        print("<tr>");
        print("<td>{$position["name"]}</td>");
        print("<td>{$position["symbol"]}</td>");
        print("<td>{$position["shares"]}</td>");
        print("<td>{$position["price"]}</td>");
        print("</tr>");
    }

but it gives me a whole list of errors: enter image description here Here is a part of my index function:

 $positions = [];
    $balance = 10000.0000;

    // query info from portfolios
    $rows = CS50::query("SELECT * FROM portfolios WHERE user_id = ?", $_SESSION["id"]);

    // enter portfolio details in the array 'positions'
    foreach ($rows as $row)
    {
        $stock = lookup($row["symbol"]);
        if ($stock !== false)
        {
            $positions[] = [
                "name" => $stock["name"],
                "price" => $stock["price"],
                "shares" => $row["shares"],
                "symbol" => $row["symbol"]
            ];

            $positions[] = ["price" => number_format($positions["price"],2,'.',',')];
        }

        else 
        {
            apologize("This is no stock in your portfolio");
        }
    }

    $positions[] = ["balance" => $balance];
    $positions[] = ["balance" => number_format($positions["balance"],2,'.',',')];

    // render portfolio
    render("portfolio.php", [ "title" => "Portfolio","positions" => $positions]);

I really can't find the error. What can be done ?? here's what var_dump outputs:enter image description here

1 Answer 1

1

Each time you do this $positions[] = ["price" =>number_format($positions["price"],2,'.',',')]; there is a row added to the $positions array that does not have "name", "shares" or "symbol". Ditto these (plus no "price"):

$positions[] = ["balance" => $balance];
$positions[] = ["balance" => number_format($positions["balance"],2,'.',',')];

Perhaps add a var_dump($positions) before the foreach to see what $positions really looks like.

2
  • I updated my index function and removed $positions[] = ["price" => number_format($positions["price"],2,'.',',')]; so that each row has a symbol, price and number, still its not working Commented Dec 1, 2016 at 7:38
  • Looks like the two rows with "balance" still do not have symbol, price, number, name. (Even though the screen shot is really hard to discern!). And some errors are coming before the var_dump. Maybe you need to add some isset if you want to use $portfolios as a multi-purpose array. Commented Dec 1, 2016 at 11:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .