PHP - Removing one array layer - php

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;

Related

Loop not working with assosiative array Php

Can i make multidimensionalarrry to assosiative array, Right now i am getting following result
Array
(
[0] => Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
[1] => Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
}
)
I just want to put all values in single, i want result like following array
Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
)
Here is my code,My code not showing only one record with loop (code should showing all minimum_marks and maximum_marks), where i am wrong ?
$result = $query->result_array();
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
}
print_R($simpleArray);
I don't know why are you expecting this output. But my suggestion, if you want it really?
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
print_R($simpleArray);
}
Print the value inside loop, so it wont push and it wont create multiple array. every time, it will overwrite. But please be sure, finally you get last array value only on the simpleArray. Hope you understood!
Let me explain with example. If you want to display the marks in table, I will suggest you to return directly like below instead of creating variable and retrieving it again.
echo '<table>
<tr><th>Min Marks</th><th>Max Marks</th></tr>';
foreach ($result as $skuArray) {
$minMarks = $skuArray['minimum_marks'];
$maxMarks = $skuArray['maximum_marks'];
echo '<tr><td>'.$minMarks.'</td><td>'.$minMarks.'</td></tr>';
}
echo '</table>';
I don't really understand what you want.
If you want to get your array in two different variables you can try this:
Use dynamic variables, the name of the variable is dynamically generated in your loop.
foreach($result as $key => $_array){
//$key is your inder of you multidimensional
$name_variable = '_array_number_'.$key; //Name of the variable
$$name_variable = $_array; //Instanciate dynamic variable
}
//You got now this two array
print_r($_array_number_0);
print_r($_array_number_1);
But please be more precise next time with what you expect and why you need this.
By the way, what happened to your code is that in the first loop you instanciate 'minimum_marks' and 'maximum_marks' in $_simple_array.
But in your second loop you overwrite the value of 'minimum_marks' and 'maximum_marks'.

php array value repeated for each key

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.

PHP Recursion with Associative Array (Menu structure)

I've been banging my head against a wall today. I have a mysql table that has a list of menu items which have a recursive parent/child relationship. I need to create an associative array that matches it.
Here is my code, and below it is an explanation of my problem.
MySQL Database
CREATE TABLE IF NOT EXISTS `menus` (
`sectionid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`parentid` int(10) unsigned NOT NULL DEFAULT '0',
`name` varchar(128) NOT NULL DEFAULT '',
PRIMARY KEY (`sectionid`)
);
INSERT INTO `menus` (`sectionid`, `parentid`, `name`) VALUES
(1, 0,'DOWNLOADS'),(4, 1,'Player Scenarios'),
(5, 1,'Co Op Scenarios'),(9, 1,'MAPS');
PHP CODE
function get_db_children($parentid) {
$mysqli = mysqli_open();
$sqlStr = "select sectionid as childid from menus where parentid=$parentid order by sectionid";
$result = $mysqli->query($sqlStr);
$mysqli->close();
return $result;
}
function get_children(&$node) {
foreach ($node as $key=>$value) {
$result = get_db_children($key);
while ($row = $result->fetch_assoc()) {
$tmp = array($row['childid'] => array());
$node[$key][$row['childid']]= get_children($tmp);
}
}
return $node;
}
===========================================
The above functions are called from my main script as follows:
$categories[0] = array ();
get_children($categories);
print "Categories=".print_r($categories);
exit;
==============
My PROBLEM.
My problem is that the structure of the returned array is not QUITE how I want it.
The code above returns:
Categories=
Array ( [0] => Array
( [1] => Array
( [1] => Array
( [4] => Array
( [4] => Array ( ) )
[5] => Array
( [5] => Array ( ) )
[9] => Array
( [9] => Array ( ) )
)
)
)
)
What I want is:
Categories=
Array ( [0] => Array
( [1] => Array
(
( [4] => Array ( ) )
( [5] => Array ( ) )
( [9] => Array ( ) )
)
)
)
A null array indicates no children.
I can't figure out how to get rid of the double up on key values. :(
If anyone can help, would be much appreciated.
Cheers,
Nap
Changing the approach a little has fixed my problem. Instead of passing the $categories array by reference, I just pass the ID of the parent menu item and return the array.
Code below uses same SQL data and SQL accessor function get_db_children($parentid) as given in my OP. I'm sure this could be improved upon, but at least I've got my result.
#Josh, thnx for your input.
PHP Functions
function get_twigs($nodeid) {
$result = get_db_children($nodeid);
if ($result->num_rows != 0) {
while ($row = $result->fetch_assoc()) {
$node[$row['childid']] = array();
$node[$row['childid']] = get_twigs($row['childid']);
}
} else {
$node=NULL; // or any other 'no children below me indicator.
}
return $node;
}
function get_branch($nodeid) {
$node[$nodeid] = array();
$node[$nodeid] = get_twigs($nodeid);
return $node;
}
PHP Caller
$categories = get_branch(0);
Finally got it going.
:)
you are passing in the $node by reference therefore instead of doing $node[$key][$row['childid']] = get_children($tmp); you should really be doing
$value[$row['childid']] = get_children($tmp)
or
$node[$row['childid']] = get_children($temp)
but if you go with the second option you will have to pass in $categories[0] on the first call to get_children (which is what you are doing when you are making the recurring calls)
update:
ill try and explain the reason for that...
as you can see the first entry (0) is not duplicated. only after the first recurring call is where your problem starts, the reason for that is because you are passing in the child array by reference therefore the second time around [as a example] when you call get_children the $node var actually already refers to the nested part
array(
0=>array(
1=>array(/*this is what $node actually is the second time around*/
/*when you say $node[$key][$row['childid']] what you are actually saying is assign the value to array[0][1][1][4] = array())*/
)
)
);
i hope this helps. if i can think of a way to explain it batter ill come back and update...

Arranging data in arrays using PHP

For some reason I having a hard time trying to arrange my data in arrays. Now I have a database that holds the title of a page, the content, id and date modified.
I have a function that calls onto another function that does a query and gets all the tables in that database table. Currently im just returning the titles of the pages because it's easy to do, but i'd like to use the id as well as the title. So I thought about using multidimensional arrays. I've used arrays in my life in different languages like C++, c#, java and so on, but got some reason the way PHP does it strikes me as odd, I think there is something im not getting.
So here i am looping through my records and putting the title in an array:
while ($row = $result->fetch_object())
{
$pages[$count] = $row->title;
$count++;
}
return $pages;
Would it be something like this:
$pages = array()
{
["records"]=>
array()
{
[$count]=> $row->id
[$count]=> $row->title
}
}
Would this give me an output of something like this:
[0]=> 1, homePage
[1]=> 2, page2
[2]=> 3, anotherPage
Is this right? is there a better way of doing it?
Thanks for your help.
From what I gathered, you're trying to achieve this:
$pages = array();
while ($row = $result->fetch_object()) {
// Empty bracket syntax allows indices to be automatically incremented
$pages[] = array("id" => $row->id, "title" => $row->title);
}
Outputs
Array
(
[0] => Array
(
[id] => 1
[title] => homePage
)
[1] => Array
(
[id] => 2
[title] => page2
)
[2] => Array
(
[id] => 3
[title] => page3
)
)
To access your page titles/IDs singularly:
echo $pages[2]['id']; // 3
echo $pages[2]['title']; // page3
To loop through all of the elements in the array:
foreach ($pages AS $page) {
echo $page['id'];
echo $page['title'];
}
I do this for my queries. This allows you to not need to know what is coming back. It does restrict by not only choosing what you want but I do that with my query if needed.
$strQuery = "your query";
$objResult = mysql_query( $strQuery );
$arrResults = array( );
foreach ( $objResult->result_array( ) as $arrRecord )
{
$arrResults[] = $arrRecord;
}
Then anything that comes back through your query is stored in the $arrResults array
Array
(
[0] => Array
(
[id] => 1
[title] => title1
)
[1] => Array
(
[id] => 2
[title] => title2
)
)

PHP class array question

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

Categories