"Illegal string offset" error when calling usort in database data

Asked

Viewed 811 times

0

I am trying to sort the result by a specific column of a database array.

 function cmp($a, $b) {
 return strcmp($a['usu_codigo'], $b['usu_codigo']);
  };

usort($usu_info_coluna, "cmp");

Giving a var_dump in $usu_info_Coluna, he returns:

array(21) { ["usu_codigo"]=> int(1) ["usu_nome"]=> string(5) "LUANN" ["usu_senha"]=> string(60) "$2y$10$I4RqdKD/cOwRDNpFgtIbWeVirNIfxHPREMEklGaBuONGRZMtQfUgq" ["usu_sobrenome"]=> string(5) "SOUSA" ["usu_cpf"]=> string(11) "12345678998" ["usu_rg"]=> string(9) "123456789" ["usu_nasc"]=> string(10) "2018-10-22" ["usu_endereco"]=> string(4) "AV 2" ["usu_numero"]=> string(2) "97" ["usu_bairro"]=> string(8) "BLOCO D2" ["usu_cep"]=> string(8) "11900000" ["usu_cidade"]=> string(11) "REGISTRO-SP" ["usu_uf"]=> string(2) "SP" ["usu_tel"]=> string(10) "1338226293" ["usu_cel"]=> string(11) "13997821923" ["usu_genero"]=> string(9) "Masculino" ["usu_situacao"]=> string(5) "ativo" ["usu_email"]=> string(22) "[email protected]" ["usu_indicador_codigo"]=> NULL ["usu_datacadastro"]=> string(10) "2018-10-22" ["usu_nivel"]=> string(3) "adm" } 

What did I do wrong using usort? I changed and changed the code of the usort, but always returns me a different error, and I believe that was as close as I got.

UPDATE 0: This is the prepared query I use for the query:

$_SESSION['codigo'] = 1; 
$usu_codigo = $_SESSION['codigo'];
$usu_situacao = 'ativo';

$stmt3 = $conexao->prepare('SELECT * FROM esc_usuarios WHERE usu_indicador_codigo = ?');
$stmt3->bind_param('i', $usu_codigo);
$stmt3->execute();
$usu_ult5_cad = $stmt3->get_result();

Displaying through a table:

<?php

$limit = 2;
while($limit -- && $coluna_ult5 = $usu_ult5_cad->fetch_array()){

    ?>
    <tbody>
    <tr>
      <th><?php echo $coluna_ult5['usu_codigo']; ?><br></th>
      <td><?php echo $coluna_ult5['usu_nome']; ?></td>
      <td><?php echo $coluna_ult5['usu_sobrenome']; ?><br></td>
    </tr>                                               
<?php }

?>

2 answers

2

The first step of everything is to try to translate the error to know what it is.

Illegal string offset is returned when you try to get a offset of a string, passing a string per parameter.

Behold:

$a = 'wallace';

var_dump($a[0]); // string 'w'

var_dump($a['string']); // Erro: Illegal string offset 'string' on line 1

See the test on ideone.

That’s because the operator [] works so much to array, as for string in PHP. In the case of string you can get the character according to the position passed.

However, if you pass a string, it causes an error. This is something PHP allows for strings and few people know.

What’s happening within your function is basically this.

When you pass your array for usort, He’ll pick up the items from his array of 2 and 2 and pass them by callback parameter of usort.

Exemplifying the case of your array, he’s like this:

  ['a' => 1, 'b' => 2, 'c' => 3]

If you pass this array for usort, the callback would place 1 in $a and 2 in $b.

And so it is giving error Illegal string offset. Because you assumed that inside the callback was passing one array, but is actually passing strings or integers.

So it can work out the way you’re trying to, your array should be like this:

  [
        ['usu_codigo' => 1, /** resto do array **/],
        ['usu_codigo'   => 2, /** resto do array **/],
        ['usu_codigo'   => 3, /** resto do array **/],
  ]

See an example on ideone

  • Only this array ordering will make me have to change the original query?

  • It depends. What is the original query? If you think it is feasible, edit your question and put it there, so I can analyze it

  • What I really want to do is filter the table results, for example limit to 2 records (all ok) and sort by ascending/descending order by a column, "usu_code" for example. I don’t want to sort by the query using an order by because I don’t want to have to do a query that looks for the same results just to sort, I just want to do a search in the database to show by the site.

  • But think of a difficulty to fit this usort into my code.

  • I couldn’t understand why I didn’t use order by.

  • How do you make the Function return "get_result"?

  • I don’t want to use order by in a second query because I just want to do a database search, I already have the data in a SELECT *, you know? I want to optimize the code to use the smallest amount of searches in the bank

  • Well, that’s all there is, I get the search result, I use the fetch array and display the data in a table, choosing which columns and how many records I want to display, only how I will use a query, I need to sort the data out of the query.

  • It is hard to understand your code, it is very pricked. Where necessarily are you calling the usort? Because in "while" you’re getting straight the bank results. And I also did not understand why you would want to do a second query, there is no way to already sort the first?

  • I haven’t called the usort yet, because before I even call, gives this error, I want to use it in that while. I’m not going to do a second query, I want to sort the first one anyway.

  • "SELECT * FROM esc_usuarios WHERE usu_indicador_codigo = ? order by usu_indicador_codigo" does not scroll?

  • And you only want to show 2 results?

  • does not scroll because I do not want to change the original query,

Show 8 more comments

-1

Edit: As corrected in the comments, the error "Illegal string offset" happens when you try to access the index of a string using another string (as explained best in the other answer).

And the mistake "Undefined offset" (that I had mistakenly confused before) happens when you try to access an index that does not exist in the array. In this error it is possible to use "isset" to check and test the array value before performing any operation.

  • Removed the error, but returned no value, need some while?

  • I don’t know if it influences something, but I’m trying to do it inside a Session using: isset($_SESSION['codigo']); $_SESSION['codigo'] = 1; $usu_codigo = $_SESSION['codigo'];

  • How so no value returned? the usort returns a Boolean, and the ordered variable is the passed variable itself ($usu_info_column). If you can, update the question by placing the information from Séssion.

  • Sorry, my mistake. How do I use this result in a while? Because if I use it like this: while ($Row = mysqli_fetch_assoc($usu_info_column)), it will say that it needs a result instead of an array

  • Wrong. Generally, Illegal offset is related to the type of value passed to the array. What appears when offset does not exist is "Undefined offset"

  • @Luannsousa did not return any value because, as I said in my reply, his array past to usort is iterating over each item. And each item is a value int or strng, and not a array. You will have to review how the database data is returned to you.

  • Thanks for the correction, my confusion really.

Show 2 more comments

Browser other questions tagged

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