Arranging data in arrays using PHP - 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
)
)

Related

Access next & prev array inside array (PHP)

I have an array like this:
Array
(
[0] => Array
(
[id] => 1
[question] => first question
[answer] => first answer
)
[1] => Array
(
[id] => 2
[question] => second question
[answer] => second answer
)
)
I want to have a "Previous" and "Next" button on the page, and when we click one or the other, the previous or next array is selected so I can echo out items on the page.
So for example if the page loads and Array[0] is printed out by default, clicking next should then print out Array[1].
Using PHP sessions to store the current index ID of the array is one solution, or you could simply use a query string parameter too?
This would looks something like this in PHP:
$dataSet = [
[],
[],
];
$record = (!empty($_GET['recordId']) ? $_GET['recordId'] : 0);
if (!isset($dataSet[$record])) {
echo 'Record not found';
exit;
}
print_r($dataSet[$record]);
if ($record > 0) {
echo 'Previous';
}
if (count($dataSet) < $record+1) {
echo 'Next';
}

loop through an array of ids and get result in an array in CI

in my controller i have an associative array in the following pattern!
Array ( [0] => Array ( [id] => 13 ) [1] => Array ( [id] => 14 ) )
now what i want to do is there is some data on another table where these ids are referenced as foreign keys what i want to do is iterate through this array of ids and fetch data from another table on the basis of these ids!
this will be my query
$this->db->select("path");
$this->db->from('main_data');
$this->db->where("f_key",$id); //this is the id i want to take from array i written above
$query = $this->db->get();
return $query->result_array();
Does this give you enough to complete your work or do you need more? I can't test my code if I include your codeigniter code in there, since I don't have your database.
<pre>
<?php
$arrOfIds = array( array( "id" => 13 ), array( "id" => 14 ));
foreach($arrOfIds as $row) {
$id = $row["id"];
echo $id . "\r\n";
//remove the echo statement and run your queries and do whatever you need to do
}
?>
</pre>

selecting value of particular index with PHP foreach

I have the following loop that creates an array
while($row1 = mysqli_fetch_assoc($result1))
{
$aliens[] = array(
'username'=> $row1['username'],
'personal_id'=> $row1['personal_id']
);
}
It produces the following result
Array (
[0] =>
Array ( [username] => nimmy [personal_id] => 21564865 )
[1] =>
Array ( [username] => aiswarya [personal_id] => 21564866 )
[2] =>
Array ( [username] => anna [personal_id] => 21564867 )
Then I have another loop as follows, inside which, I need to fetch the personal_id from the above array. I fetch it as follows.
foreach($aliens as $x=>$x_value)
{
echo $aliens['personal_id'];
//some big operations using the
$aliens['personal_id']; variable
}
However, I can't get the values if personal_ids. I get it as null. What seems to be the problem? How can I solve it?
You have an array of "aliens", each alien is an array with personal_id and username keys.
foreach ($aliens as $index => $alien) {
echo $alien['personal_id'], PHP_EOL;
}
The foreach loop iterates its items (aliens). The $alien variable represents the current iteration's item, i.e. the alien array.
foreach($aliens as $x=>$x_value)
{
echo $x_value['personal_id'];
//some big operations using the
$x_value['personal_id']; variable
}

Array - Loop through, group together by key value, and then print/echo new values (various array levels)

I'm having trouble printing the results of this array in loop (to be displayed on the front end). The objective to be able to get the chapter name (eg, Chapter_Name_Unique), that chapter name's total chapter post views count, and then the fullname of each chapter_member within that chapter name (or group). I'm thinking that something isn't structured properly here, because I'm having issues looping through.
Is my logic off?
print_r looks like this:
Array
(
[Chapter_Name_Unique] => Array
(
[chapter_post_views_count] => 3338
[chapter_members] => Array
(
[0] => Array
(
[post_views_count] => 3338
[first_name] => Mary
[last_name] => Jane
[fullname] => maryjane
[chapter_name] => Chapter_Name_Unique
)
)
)
[Chapter_Name_Unique_2] => Array
(
[chapter_post_views_count] => 783
[chapter_members] => Array
(
[0] => Array
(
[post_views_count] => 404
[first_name] => Betty
[last_name] => Lou
[fullname] => bettylou
[chapter_name] => Chapter_Name_Unique_2
)
[1] => Array
(
[post_views_count] => 379
[first_name] => Judy
[last_name] => Jones
[fullname] => judyjones
[chapter_name] => Chapter_Name_Unique_2
)
)
)
)
and the actual functions look like this:
$grouped_types = array();
// to add together post counts of group members
foreach($users as $chapter){
$grouped_types[$chapter['chapter_name']]['chapter_post_views_count'] += $chapter['post_views_count'];
}
// to group on top level by chapter_name
foreach($users as $chapter){
$grouped_types[$chapter['chapter_name']]['chapter_members'][] = $chapter;
}
echo "<pre>";
print_r( $grouped_types );
echo "</pre>";
Try something like (assuming that $users is your array from your print_r())
$grouped_types = array();
foreach($users as $chapter=>$data){
$grouped_types[$chapter]['chapter_post_views_count'] = $data['chapter_post_views_count'];
foreach($data['chapter_members'] as $member){
$grouped_types[$chapter]['chapter_members'][] = $members['fullname'];
}
}
echo "<pre>";
print_r( $grouped_types );
echo "</pre>";
Thanks so much guys, your tips really helped. I wound up using a bit from both, and pulling this together:
foreach( $grouped_types as $chapter_name_unique => $vars) {
$chapter_post_views = $vars['chapter_post_views_count'];
$chapter_members = $vars['chapter_members'];
echo $chapter_name_unique; // echo chapter name (level 1)
echo $chapter_post_views; // echo chapter post views (level 2 - $vars before)
foreach( $vars['chapter_members'] as $member){ // loop through all chapter_members
$vars['chapter_members'][] = $member['fullname'];
echo $member['fullname']; // echo all usernames within the group
}
}
In combination with the two other foreach statements above (they resort and add things together saving to the $grouped_types array), this works exactly as I needed it to. (Hopefully not too much unnecessary looping?)
Thanks again!

PHP - Removing one array layer

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;

Categories