Pick up an array index in PHP with foreach

Asked

Viewed 654 times

0

I have this code to save the Mysql output in array

    $sql = "SELECT valor_cobrar FROM pedidos order by id_usuario";
    $userinfo = array();
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
    // output data of each row
     while($row = $result->fetch_assoc()) {
        $userinfo[] = $row;
    }
    } else {
    echo "0 results";
    }
print_r($userinfo);

returns

Array ( [0] => Array ( [id] => 36 [data] => 2019-05-10 00:00:00 [cod_transacao] => asdsad [tipo] => boleto [valor] => 30 [valor_cobrar] => 35 [status] => 3 [tipo_transacao] => saldo [id_usuario] => 34 ) [1] => Array ( [id] => 34 [data] => 2019-05-17 14:21:50 [cod_transacao] => D1E503F5-9D2D-4957-9902-7773E0477071 [tipo] => boleto [valor] => 20 [valor_cobrar] => 21.47 [status] => 1 [tipo_transacao] => saldo [id_usuario] => 95 ) [2] => Array ( [id] => 35 [data] => 2019-05-17 14:23:18 [cod_transacao] => 8574188D-ED9A-4216-B48D-CADC38CE56B7 [tipo] => boleto [valor] => 40 [valor_cobrar] => 42.47 [status] => 1 [tipo_transacao] => saldo [id_usuario] => 95 ) )

I need to take with the foreach only the value of the index [valor_cobrar] array. I’m doing so, but only returns the value of [id], how would I solve it?

foreach($userinfo as $item) {
    $key   = key($item);
    $value = current($item);

    echo "$key => $value\n";
}

returns

id => 36 id => 34 id => 35
  • 4

    Doubt: if you only need valor_cobrar, why you selected all the columns in the database?

2 answers

2


If you want to get column value valor_cobrar for each record returned from your query

foreach ($userinfo as $item) {
    echo $item['valor_cobrar'];
}

If you want to get column only value valor_cobrar for a specific record:

$uid  = 5; // O id do usuário que você quer buscar o valor
$sql  = "SELECT valor_cobrar FROM pedidos where id_usuario = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([$uid]);

$valorCobrar = $stmt->fetchColumn(0); // 0 por que selecionamos apenas uma coluna na query

echo $valorCobrar;

Reading suggestions

1

Try it like this:

foreach($userinfo as $item) {
       echo $item['valor_cobrar'];
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.