I have an multidimensional array made from database query and is like that:
Array
(
[0] => Array
(
[0] => -8.63296022565696
[x] => -8.63296022565696
[1] => 41.1584289069069
[y] => 41.1584289069069
[2] => 0
[seq] => 0
[3] => 2
[seq2] => 2
[4] => -8.63306031211831
[next_x] => -8.63306031211831
[5] => 41.1584543235506
[next_y] => 41.1584543235506
[6] => -8.64195115878864
[alert_x] => -8.64195115878864
[7] => 41.1599295066425
[alert_y] => 41.1599295066425
[8] => 54e728edafac1
[route] => 54e728edafac1
[9] => 54e728edafac1
[routeid] => 54e728edafac1
[10] => 2
[counttargetinter] => 2
[11] => passeio
[type] => passeio
[12] => 1355
[arcid] => 1355
)
All the values are repeated because have a key number and a key name.
Example: The value '-8.63296022565696' are in key "0" and "X".
How I can remove the duplicated?
This is how i made the array:
$query = "SELECT * FROM foo;";
$startRows = pg_query($connection, $query);
$startInfo = array();
while($list = pg_fetch_array($startRows)) {
$startInfo[] = $list;
}
Of course you can't mess with the generate JSON string to deal with the dups. You solve it during the creation of the array itself before encoding. Looking at the structure, this seems to be the problem of fetching both numeric and column indices.
Since you haven't posted any codes related to actually creating this JSON string, just use this basic idea on how to get rid of them.
If you intent do remove those numeric indices, you'll probably need to use fetch_assoc() flavours of your database API, so that in turn, you'll only get the column name indices instead of having them both.
Here's the idea:
$data = array(); // initialization of the container
while($row = your_fetch_assoc($result)) { // use assoc() instead to exclude those numeric indices
$data[] = $row;
}
echo json_encode($data);
Depending on what API you're using, if its PDO, either use -->fetch(PDO::FETCH_ASSOC) or just ->fetchAll(PDO::FETCH_ASSOC) without the need of a loop. If its MySQLi, then just use ->fetch_assoc()
EDIT: At last your codes, as I have suspected you're using _array() function which results associative and numeric indexed rows.
$query = "SELECT * FROM foo;";
$startRows = pg_query($connection, $query);
$startInfo = array();
while($list = pg_fetch_assoc($startRows)) {
$startInfo[] = $list;
}
Use pg_fetch_assoc() instead of _array() so that you'll get the associative indices only.
Like Ghost:
You can use pg_fetch_row() to get numeric indices or pg_fetch_assoc() to get field name.
$query = "SELECT * FROM foo;";
$startRows = pg_query($connection, $query);
$startInfo = array();
while($list = pg_fetch_row($startRows)) {
$startInfo[] = $list;
}
Try this:
foreach($walkroute as $routepoints){
foreach($routepoints as $key => $value){
if (is_int($key)){
unset($routepoints[$key]);
}
}
}
You have to modify it due to the fact that i don't know, what the structure and names of your array actually are.
Related
I have a function for dropdown list, which shows me the names for filtering results from two different queries. The one with the numeric value from 1-4 and the other with 10-110, some of the results have the same strings:
function filter_workhires($status) {
$status = array();
$status[1] = 'booked';
$status[70] = 'booked';
$status[2] = 'partiallyattended';
$status[90] = 'partiallyattended';
$status[3] = 'fullyattended';
$status[100] = 'fullyattended';
$status[4] = 'notattended';
$status[80] = 'notattended';
$status[10] = 'status_user_cancelled';
$status[20] = 'status_session_cancelled';
$status[30] = 'status_declined';
$status[40] = 'status_requested';
$status[50] = 'status_approved';
$status[60] = 'status_waitlisted';
$status[110] = 'status_not_set';
return $status;
}
In this form, I get double names for examle booked. How to combine the statuses according to the strings they show?
return array_unique($status);
That's about it :)
Output
Array
(
[1] => booked
[2] => partiallyattended
[3] => fullyattended
[4] => notattended
[10] => status_user_cancelled
[20] => status_session_cancelled
[30] => status_declined
[40] => status_requested
[50] => status_approved
[60] => status_waitlisted
[110] => status_not_set
)
Change it around so the description is the array key and the ID of the status is the value. When you build the array and you hit a duplicate you can then add multiple ID's to the value in some kind of structure like a comma separated string. So you end up with:
$status['booked'] = '70';
$status['partiallyattended'] = '2, 90';
$status['fullyattended'] = '3, 10';
...
When someone chooses an item you explode the value and get all the ID's that relate to that status.
I'm using the library PHPExcel to read data in an Excel file. The problem I'm having, is that when I use something like:
$obj = PHPExcel_IOFactory::load($file);
$data = $obj->getActiveSheet()->toArray(null,true,true,true);
To load my file and convert its content into an array, I get all the columns and rows of my Excel file in my array even those without any data in them. Is there a method or something in the library PHPExcel to tell it to ignore cells in my Excel sheet that do not contain any data? (Instead of having a bunch of empty associative arrays in my $data)
If your problem is in getting empty columns that go after real data, and you would like to avoid these, you could do something like this:
$maxCell = $sheet->getHighestRowAndColumn();
$data = $sheet->rangeToArray('A1:' . $maxCell['column'] . $maxCell['row']);
This will return array representing only the area containing real data.
I have this solution for my case
$maxCell = $objWorksheet->getHighestRowAndColumn();
$data = $objWorksheet->rangeToArray('A1:' . $maxCell['column'] . $maxCell['row']);
return all rows with all empty string as:
[1] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
[6] =>
[7] =>
[8] =>
[9] =>
[10] =>
[11] =>
[12] =>
[13] =>
)
To remove these empty rows
$data = array_map('array_filter', $data);
will return
[1] => Array
(
)
And this is the finale solution:
$maxCell = $objWorksheet->getHighestRowAndColumn();
$data = $objWorksheet->rangeToArray('A1:' . $maxCell['column'] . $maxCell['row']);
$data = array_map('array_filter', $data);
$data = array_filter($data);
will return an array with only filled rows .. hope that help
No there isn't. The toArray() method returns the first argument (NULL) to represent an empty cell. You can then apply standard PHP array functions such as array_filter() to eliminate empty cells.
foreach($data as $key => &$row) {
$row = array_filter($row,
function($cell) {
return !is_null($cell);
}
);
if (count($row) == 0) {
unset($data[$key]);
}
}
unset ($row);
This will eliminate every cell that is a NULL (empty) value, and every row that comprises nothing but empty cells. It will preserve the array keys, so your array keys will still give you a cell reference.
Note that an cell containing an empty string is not a null cell, so these will be retained, although the array_filter() callback could be modified to remove them as well.
I have a simple PHP function that will grab information from a database based on a unique ID:
function oracleGetGata($query, $id="id") {
global $conn;
$results = array();
$sql = OCI_Parse($conn, $query);
OCI_Execute($sql);
while ( false!==($row=oci_fetch_assoc($sql)) ) {
$results[ $row[$id] ] = $row;
}
return $results;
}
So for example $array = oracleGetData('select * from table') would return:
[1] => Array
(
[Title] => Title 1
[Description] => Description 1
)
[2] => Array
(
[Title] => Title 2
[Description] => Description 2
)
This is fine, however, if I just want to return one record $array = oracleGetData('select * from table where id = 1') it returns the data like:
[] => Array
(
[Title] => Title 1
[Description] => Description 1
)
Not only am I unsure of how to reference this (there is nothing identifying the array) I'd also like to somehow change my function so if it just returns one record, it will just be a simple one dimensional array.
I've looked into the usual PHP array functions but can't find anything that'll help, nor an easy way of identifying how deep the array is.
Would really appreciate any help, thank you
Use array_pop():
$array = array_pop(oracleGetData('select * from table where id = 1'));
You will then get one single array:
Array
(
[Title] => Title 1
[Description] => Description 1
)
Instead of an array embedded in another one:
Array
(
[] => Array
(
[Title] => Title 1
[Description] => Description 1
)
}
I think there is an logic error in your script:
Change
$results[ $row[$id] ] = $row;
into
$results[] = $row;
The problem is, that you want to have the Database key value as array key value, but you don't know the Database key, since you don't know what the query will look like.
You could try:
$results[$row['id']] = $row;
But this only works when all of your results have a Database key named "id".
You pass a $id in the function signature, but in the loop you uses $row[$id], Why? Maybe the error is there.
If you want a sequencial id in your result set, you don't need use the $id, you can uses array_push() function
array_push($result, $row);
OR
$results[] = $row;
Ok so im trying to grab a single part of an array, the array is the return for some stats there can be up to 8 players in the server, the data i get is like this
Array (
[0] => 1
[1] => Player1
[2] =>
[3] => 1
[4] => 0
[5] => 0
[6] => 0
[7] => 0
[8] => 1
[9] => Player2
[10] =>
[11] => 1
[12] => 0
[13] => 0
[14] => 0
[15] => 0
)
so that is the return for 2 players, as i said it can be up to 8, anyway i am trying to just grab the player names and im not sure how to go about it ( Player1 , Player2 ) is the only data i need, any help is appreciated, it always returns 8 pieces of data per player never more never less if that makes it easier
(sorry for bad english)
If you have control over the return type, I would restructure the array being returned either into an Object or an array of arrays where each sub array contains all of the information for one player.
I you don't have control over the return type and the Player's name is always in the second position within the return array you can use a while loop to iterate over the array. Use a counter starting at 1 and then increment the counter by 8 each time through the loop. For example:
$i= 1;
while ($i < count($return_var)) {
$name = $return_var[$i];
// do something w/ name
$i += 8;
}
You want to get all items that are not '' (assuming empty string), 0 or 1 (assuming integers here):
$playerNames = array_diff($array, array('', 0, 1));
If you more specifically know what the format of the array actually is, you can also create some little "parser":
$playerSize = 8;
$playerFields = array('_1', 'name', '_3', '_4', '_5', '_6', '_7', '_8');
$players = array_chunk($array, $playerSize);
foreach($players as &$player)
{
$player = (object) array_combine($playerFields, $player);
}
unset($player);
This does parse $array into another array $players that contains one object per each player. Each object has the name property now:
printf("%d Player(s):\n", count($players));
foreach($players as $i => $player)
{
printf("#%d: %s\n", $player->name);
}
if the array you pasted is called $array and the values of the places without players are always numeric (like your example), this code will work:
$players = array();
foreach($array as $player){
if(!empty($player) && !is_numeric($player){
$players[]=$player;
}
}
var_dump($players);
For some reason my array I am returning is not what I expect. Could someone explain to me why I am getting the current results, and what I can do to fix it? Here is the code in question:
public static function getProduct($_row, $_value)
{
$stmt = _DB::init()->prepare("SELECT pid, name, quantity, price, cost
FROM products
WHERE $_row = ?"
);
if($stmt->execute(array($_value)))
{
while ($row = $stmt->fetch())
return $row;
}
}
$product = Class::getProduct('pid',1);
print_r($product);
When I print the following array I am getting two results per row like so:
Array ( [pid] => 1 [0] => 1 [name] => Boondoggle [1] => Boondoggle [quantity] => 12 [2] => 12 [price] => 9.9900 [3] => 9.9900 [cost] => 12.9900 [4] => 12.9900 ) Boondoggle
I was only wanting to show the associative results. What is wrong with my function?
From the looks of it you are using PDO to communicate with your DBMS. The PDOStatement::fetch() method's first argument is a parameter to tell it what to return. By default it returns each column in both name format and numbered index format to allow iterating through columns easier. To just get the column names as indexes, you can pass it PDO::FETCH_ASSOC to your call. So the fetch statement would look like this:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)
See here for more details:
http://www.php.net/manual/en/pdostatement.fetch.php
Pass PDO::FETCH_ASSOC to your fetch call:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
edit: I'm just assuming you're using PDO, of course