0

I am pulling tables from a database and I'm trying to keep the userdata table from being included in the array that is eventually sent to my application. I've tried using array_diff and unset, but I haven't had any luck with it. As tables can be added, the userdata one won't always be in the same position.

The array when I check on JSONlint.com appears like this:

[{"table_name": "OSA"
}, {
    "table_name": "OSB"
}, {
    "table_name": "userdata"
}]

code in PHP file:

    $tables = array();

    while ($row = mysqli_fetch_array($result)){
    array_push($tables, array("table_name"=>$row[0]));

    }

    $remove= array({"table_name": "userdata"});
    $result = array_diff($tables, $remove);

    echo json_encode($result);
3
  • How did you call unset? Commented Oct 3, 2017 at 19:38
  • 1
    Since the data comes from a database, it should be possible to change the query so it does not retrieve the table_name key. Commented Oct 3, 2017 at 19:40
  • this PHP code should fail, because you try to declare an associative array as you would do with a dict in python or an object in JS. In PHP arrays are (more or less) all the same. Change line 8 to $remove= array(array("table_name" => "userdata")); Commented Oct 3, 2017 at 19:42

1 Answer 1

2

The optimal way would probably be to exclude it in the query:

SELECT column FROM table WHERE column <> 'userdata'

Or, just don't add it to the array:

while($row = mysqli_fetch_array($result)) {
    if($row[0] != 'userdata') {
        $tables[] = array('table_name' => $row[0]);
    }
}

Your array_push should work fine but I prefer the above.

But to answer the unset question. Just get the table_data column values, search for userdata and unset that key:

unset($tables[array_search('userdata', array_column($tables, 'table_name'))]);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! The unset worked for me, I failed to include the array_column when I was trying it. The while loop generated an error for me when I ran it through JSONLint.com, it came up stating too many open connections.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.