Dynamic array in php for pg_insert()

Asked

Viewed 67 times

0

I developed the following code as an example:

$dados  = "nome-luiz-idade-21-status-true";`

$arraydados = explode("-", $dados);`

I need to create a dynamic array, where: The even positions of $arraydados be the names of each position in a new array, and the odd positions of $arraydados is the respective value of that position.

I’ll do it in the shape of a for, on the basis of count of $arraydados.

I tried to do it this way but it didn’t work:

$cntindice=0;

$cntval=1;

$arrayinsert[$arraydados[$cntindice]] = $arraydados[$cntval];

Does anyone know where I’m going wrong?

Note: I will use this array in a pg_insert().

  • Why not create an object ?

2 answers

1


With the method you were initially trying, it is also possible to get the expected result.

However, using the for on account of the fact that array, in the example, you will have 6 items, the for will try to run the same process 6 times. Then, doing so:

for ($i = 0; $i < count($arraydados); $i++) {
    $arrayinsert[$arraydados[$cntindice]] = $arraydados[$cntvalor];
    $cntindice += 2;
    $cntvalor += 2;
}

It will occur of $cntindice and $cntvalor get the values: 0 (valor inicial), 2, 4, 6, 8, 10 and 1 (valor inicial), 3, 5, 7, 9, 11, respectively. But, as the array only has 6 items, the last valid positions will be 4 for $cntindice and 5 to $cntvalor, and henceforth shall return null (or emptiness).

And therefore, from position 6, both the key and the value will be null (or emptiness), and from there it will be replaced until the loop iteration ends.

So that it doesn’t happen instead of for, you can use a while, thus:

$dados = "name-luiz-idade-21-status-true";

$arraydados = explode("-", $dados);
$arrayinsert = array();

$posicaoChave = 0;
$posicaoValor = 1;

while ($posicaoChave < count($arraydados) && $posicaoValor < count($arraydados)) {
     $chave = $arraydados[$posicaoChave];
     $valor = $arraydados[$posicaoValor];

     $arrayinsert[$chave] = $valor;

     $posicaoChave += 2;
     $posicaoValor += 2;
}

//print_r($arrayinsert);

That is, as long as $posicaoChave and $posicaoValor are smaller than the size of the array, executes the code block. Thus, when $posicaoChave become 6 and $posicaoValor if it becomes 7, the condition of the loop will not be satisfied, so it will not execute the block, and consequently will not generate an unnecessary/invalid position in the array.

I hope I’ve helped!

0

You can instead create a JSON object and convert to array with json_decode()

$dados  = '{"nome":luiz,"idade":21,"status":true}';

$arr = json_decode($dados, true);  //o parametro true vai converter em array associativa

print $arr->{'nome'}; // luiz

Browser other questions tagged

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