There is a problem at the moment that you are building the array. At this point, you create a new index in the array $valores
and, to it, assigns an array. This array, in turn, contains a single index $i
which contains another array containing the information.
Decrease to 3 the upper limit, see the result.
for($i =0; $i < 3; $i++){
$valores[] = array(
$i =>
array(
'cod_produto' => $i,
'valor' => $i*2
)
);
};
echo "<pre>"; var_dump($valores); echo "</pre>";
Upshot:
array(3) {
[0]=>
array(1) {
[0]=>
array(2) {
["cod_produto"]=>
int(0)
["valor"]=>
int(0)
}
}
[1]=>
array(1) {
[1]=>
array(2) {
["cod_produto"]=>
int(1)
["valor"]=>
int(2)
}
}
[2]=>
array(1) {
[2]=>
array(2) {
["cod_produto"]=>
int(2)
["valor"]=>
int(4)
}
}
}
In fact, $valores[$x]
has another index array $x
, and this yes, in turn, has the content.
I suggest you change the code to the next one and get what you want:
for ($i =0; $i < 20; $i++) {
$valores[] = array( // Cria um novo índice e adiciona.
// $valores[$i] = array( // Esta é outra opção (equivalente)
'cod_produto' => $i,
'valor' => $i*2
);
};
$codProcura = 10;
$valor1 = 0;
for ($x = 0; $x < 20; $x++) {
$search = $valores[$x];
if ($valores[$x]['cod_produto'] == $codProcura) {
$valor1 = $search['valor'];
break;
}
}
echo $valor1;
very good, it was a lapse that I had not understood, I thank immensely.
– Silezia
@Silezia, if the answer solved your problem and there was no doubt left, mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.
– Augusto Vasques