Access next & prev array inside array (PHP) - 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';
}

Related

Confused with session and array

I have a session variable named $_SESSION['items'] that is an array. It stores items in arrays, inside its array. For example:
Array ( [0] => Array ( [0] => 2 [1] => 1 ) )
This show that there is 1 of product 2 in the items array.
Array ( [0] => Array ( [0] => 2 [1] => 1 ) [1] => Array ( [0] => 4 [1] => 1 ) )
This shows that there is 1 of item 2, and 1 of item 4 in the items array..
How so I check if a specific variable is in the items array? For example, i need to know if item 4 or item 1 is in this array so I can show the user a different page depending on if they have this item in their array or not. I get so confused with arrays that I always call undefined offsets and the like.
Figured it out. had a brain fart. thanks
foreach($_SESSION['items'] as $key => $item) {
if($item[0] == $item_id) {
echo "ITEM IS IN HERE";
}
}
//Try using array search good way
Try following this will help you to get the position where found and return nothing if not found
You dont need to loop through.
// this will search $item_id in $_SESSION['items']
$key = array_search($item_id, array_column($_SESSION['items'], 0)); //here 0 is position, see array_search
print_r($key);
if($key){
//yes found at key so that you can easily get that item again without looping
}

print the array when it is exploded

In the below code i am getting the output
Array ( [0] => 1 [1] => 2 )
but the expected output is
Array ( [0] => 1 [1] => 2 [2] => 3) Array ( [0] => 1 [1] => 2 )
why is it always executing the second if condition? although the first condition is also true.
this is the code I have tried
<?php
$test_arr=array();
$temp_option_arr=array();
$option_arr=array();
$options_array_val = Array ( 0 => "animals:1", 1 => "animals:2", 2 => "animals:3", 3 => "birds:1", 4 => "birds:2" );
foreach($options_array_val as $options_val)
{
$search_filter = explode(":", $options_val);
print_r($search_filter);
if(!in_array($search_filter[0],$option_arr))
{
array_push($temp_option_arr,$search_filter[1]);
array_push($option_arr,$search_filter[0]);
$temp_option_arr=array();
}
array_push($temp_option_arr,$search_filter[1]);
}
$test_arr[$search_filter[0]]=$temp_option_arr;
$find_species = array();
if(!empty($test_arr['animals']))
{
$find_species = $test_arr['animals'];
print_r($find_species);
}
if(!empty($test_arr['birds']))
{
$find_species = $test_arr['birds'];
print_r($find_species);
}
?>
The line
$test_arr[$search_filter[0]]=$temp_option_arr;
is out of the foreach scope, therefore it only sets the array for the birds and not for the animals, so you need to move it one line upper.
Also, you assign temp_option_arr to a value
array_push($temp_option_arr,$search_filter[1]);
then set it back to empty array without using it
$temp_option_arr=array();
You can remove the first one I guess
You clear $temp_option_arr in the first part of your code, so it will have nothing that concerns animals by the time you exit the first loop.
But instead of using all these different arrays, just build an associative array keyed by the species (animals, birds, ...), and with as values the arrays of IDs (1, 2, 3, ... i.e., the parts after the :):
foreach($options_array_val as $options_val) {
list($species, $id) = explode(":", $options_val);
$option_arr[$species][] = $id;
}
After this loop the structure of $option_arr is this:
Array (
"animals" => Array (1, 2, 3)
"birds" => Array (1, 2)
)
I think you can do what you want with that. For instance to only get the animals:
$option_arr["animals"]
which is:
Array (1, 2, 3)

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
}

Access corresponding value in PHP array given a certain known value

supposing I have an array like the one below:
Array
(
[0] => Array
(
[id] => 1
[title] => Group1
[description] => This is the group1.
)
[1] => Array
(
[id] => 2
[title] => Group2
[description] => This is group2.
)
)
Supposing the title is known as "Group2". How would I able to determine using PHP its equivalent description (that is "This is group2") if it doesn't have any idea of its ,key,id, etc. only the title?
Thanks for any help.
Try this :
$title = "Group2";
foreach($your_array as $val){
if($val['title'] == $title){
echo $val['description'];
break; //cut back on unnecessary looping
}
}
Try like this
foreach($myarray as $val){
if($val['title'] == "Group2"){
echo 'This is description '.$val['description'];
}
}
You'll have to iterate over the main array and scan it for that title.
Assuming your main array is called $groups :
$title = 'Group2';
foreach($groups as $key => $group){
if ($group['title'] == $title){
$groupDescription = $group['description'];
// if you need to reference this group again, save it's key.
$groupKey = $key;
}
}
You can insert a break command after you have found the group you are looking for to terminate the loop so that it will not continue to scan the array after you have found the one you are looking for.

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
)
)

Categories