PHP get value of array by position [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am pulling the latest 3 news articles from my database and I need to access them by the order they were pulled from, so first position in the array, second position and so on to display them in order in random sections of my web page. I came across accessing the array key but that is not working, where am I going wrong? Thanks in advance!
$value = array_slice($blog, 0, 1);
echo $value;

I think you are looking for a foreach loop or something like that:
$blog = array('foo', 'bar', 'cat');
foreach ($blog as $article) {
echo $article;
}
/**
* Gives you:
*
foo
bar
cat
*/
But if you want to do it with functions, you can use array_shift. This will remove the first element from an array and return that:
$article1 = array_shift($blog); // $blog is now `array('bar', 'cat')`
echo $article1; // >> foo
$article2 = array_shift($blog); // $blog is now `array('cat')`
echo $article2; // >> bar
$article3 = array_shift($blog); // $blog is now `array()`
echo $article2; // >> cat
Or if you want to keep the original $blog array, use array pointer functions like current, next, prev, reset and end:
reset($blog);
$article1 = current($blog); // >> foo
$article2 = next($blog); // >> bar
$article3 = next($blog); // >> cat

Use this :
$value = array_shift($blog);
To get second one
$value2 = array_shift($blog);
and third :
$value3 = array_shift($blog);

You have three different ways to accomplish this:
1. Call array_shift($blog) each time you want to get the next value.
$value = array_shift($blog);
Each time you do the array_shift it will return the next entry in the array.
Function array_pop is similar but returns the last entry in the array each time.
2. Simply access each entry of the array using the index
This gives the first entry in the array:
$value = $blog[0]
This gives the second entry in the array:
$value = $blog[1]
This gives the n'th value in the array:
$value = $blog[n-1];
3. Or finally you can simply loop through the array and echo out each entry (may not be suitable if you don't want to sequentially echo out the entries in the same place)
foreach ($blog as $blog_entry) {
echo $blog_entry;
}

Related

how to concatenate multiple strings with commas if there is the same array data [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have the array data as drawn
image description here
and I want to display data like this
0 = "16-11-1996 / IGD"
01 = "CBC", "DIFF"
04 = "GLUS "," UR "," CRE "
I tried to use this PHP splitting arrays into groups based on equal values method but it was not what I expected.
i am just learning coding and i am not what way or what keywords should i use to find a solution. i hope someone can help me,
A simple solution that uses foreach to create a new array.
Input:
$data = [
["OTHER_ID"=>"16-11-1996 / IGD", "SPEC_TYPE"=>"0"],
["OTHER_ID"=>"CBC", "SPEC_TYPE"=>"01"],
["OTHER_ID"=>"DIFF", "SPEC_TYPE"=>"01"],
["OTHER_ID"=>"GLUS", "SPEC_TYPE"=>"04"],
["OTHER_ID"=>"UR", "SPEC_TYPE"=>"04"],
["OTHER_ID"=>"CRE", "SPEC_TYPE"=>"04"],
];
Create a array grouped by "SPEC_TYPE".
$arr = [];
foreach($data as $row){
$key = $row["SPEC_TYPE"];
$arr[$key][] = $row["OTHER_ID"];
}
The array has "SPEC_TYPE" as a key and all "OTHER_ID" in a subarray. With another foreach we can now do the output. We cleverly use the implode function for this.
foreach($arr as $key => $others){
echo $key.' = "'.implode('", "',$others).'"<br>';
}
Output for the example data above:
0 = "16-11-1996 / IGD"
01 = "CBC", "DIFF"
04 = "GLUS", "UR", "CRE"
Here you can try it yourself.
Try this I kept it as simple as I could since you are a beginner. First we take the unique spec types by using array_map to take out only spec types and then array_unique for taking out the unique values. After that for every spec id we would want to search the matching spec types and filter them out. For this we use array_filter and then again another array_map to take out the other ids and finally an implode function for converting the array into a string.
$data = [
["OTHER_ID"=>"A", "SPEC_TYPE"=>"1"],
["OTHER_ID"=>"B", "SPEC_TYPE"=>"2"],
["OTHER_ID"=>"C", "SPEC_TYPE"=>"1"],
["OTHER_ID"=>"D", "SPEC_TYPE"=>"3"],
["OTHER_ID"=>"E", "SPEC_TYPE"=>"3"]
];
$result = array_map(function ($a) { return $a["SPEC_TYPE"]; }, $data);
$result = array_unique($result);
$response=[];
foreach($result as $r) {
$response[$r] = array_filter($data, function ($d) use($r) { return $r==$d["SPEC_TYPE"]; });
$response[$r] = implode(array_map(function ($a) { return $a["OTHER_ID"]; }, $response[$r]), ", ");
}
echo json_encode($response);
// {"1":"A, C","2":"B","3":"D, E"};
In laravel you have helper functions to reduce the unnecessary code so we can reduce our array_map with array_pluck. Also array_where could be used in place of array_filter but in this case it would have the same callback and functionality so let's keep the filter for now. Below code isn't tested but should do the thing.
$result = array_pluck($data, "SPEC_TYPE");
$result = array_unique($result);
$response=[];
foreach($result as $r) {
$response[$r] = array_filter($data, function ($d) use($r) { return $r==$d["SPEC_TYPE"]; });
$response[$r] = implode(array_pluck($response[$r], "OTHER_ID"), ", ");
}
Resources to study more on this:
Laravel helper functions: https://laravel.com/docs/5.0/helpers
PHP array functions: https://www.w3schools.com/php/php_ref_array.asp

Laravel Helper to merge Period arrays [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Laravel Version:7.0
I would like to know how to create this helper.
Input is date range array. For example:
$input1 = [2020-07-19, 2020-07-25];
$input2 = [2020-07-26, 2020-08-01];
$input3 = [2020-08-01, 2020-08-07];
$input4 = [2020-10-01, 2020-10-07];
$input5 = [2020-10-19, 2020-10-25];
I would like to make one helper function.
function mergeDate($array)
{
...
}
So when I use this helper, I would like to get as following result.
$array = [$input1, $input2, $input3, $input4, $input5];
$mergedResult = mergeDate($array);
$mergedResult[0] = [2020-07-19, 2020-08-07];
$mergedResult[1] = [2020-10-01, 2020-10-07];
$mergedResult[2] = [2020-10-19, 2020-10-25];
Can anyone help me how to make mergeDate function?
Input period elements aren't overlapped.
Thank you!
This would be my first guess at how to solve it.
public function merge($array){
$results = [];
foreach ($array as $element){
if (sizeof($results) == 0){
array_push($results,$element);
}else{
$found = null;
foreach ($results as $key => $r){
if (Carbon::parse($element[0])->equalTo(Carbon::parse($r[1])))
{
$found = $key;
break;
}
}
if (!is_null($found)){
$results[$found][1] = $element[1];
}else{
array_push($results, $element);
}
}
}
return $results;
}
It is a simple take on the problem. If our resulting array is empty we add the first element otherwise we iterate over the results to find a matching pair of the elements end date and the start date of the item in the results array. If we find a matching start end pair we replace the results end value with the elements end value. Otherwise we have no overlap and we can add it as a new item to the results array.
An interesting library to use would be the Spatie/Period library.
https://github.com/spatie/period
#edit
since the array is not sorted as mentioned in a comment above, you would have to sort it prior.

different results array shortcode PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a question about the differents between the normal array code and the shortcode.
The output from the shortcode version has all the results.
But the normal code has only the last record of the data from the database.
Please is there somebody who can explain this?
Below the shortcode
<?php
while ($data = mysqli_fetch_assoc($result)) {
$output[$data['category']][] = $data['type'];
}
?>
Below the normal code
<?php
while ($data = mysqli_fetch_assoc($result)) {
//alleen laatste database result
$output = array($data['category'] => array($data['type']));
}
?>
When you assign
$output = <anything>;
you discard all the previous contents of $output, and replace it with the value of <anything>. So each time through the loop in the second version, you replace the variable with the data from the current row. When the loop is done, it just has the data from the last row.
You don't want to replace all of $output. It should be a multi-dimensional array, where the first dimension is associative with categories as keys, and the second dimension is an array of all type values in that category. Assigning to
$output[$data['category']][]
does two things:
$output[$data['category']] creates the category key in the first dimension if it doesn't already exist.
Assigning to [] pushes a new element onto the array in the second dimension.
It's equivalent to the following long code
while ($data = mysqli_fetch_assoc($result)) {
$cat = $data['category'];
if (!isset($output[$cat])) {
$output[$cat] = array();
}
array_push($output[$cat], $data['type']);
}

how to make both arrays equivalent with each other in php? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
It should be minimum number of action(moves);
Example : suppose we have 2 arrays
here both arrays as an example values.
$m = ['1234','3456'];
$n = ['2345','4567'];
step1 element of $m increment by 1(1+1,2,3,4) after that new value is = 2234
step2 element of $m increment by 1(2,2+1,3,4) after that new value is = 2334
step3 element of $m increment by 1(2,3,3+1,4) after that new value is = 2344
step4 element of $m increment by 1(2,3,4,4+1) after that new value is = 2335
total no of moves = 4
This is a way to doing it by code consider it as an example. you can use any way to make equal values.
Hope now you guys will get my point.
this will help to someone whoever is needed to break online php exams
$m = ['1234','2345'];
$n = ['2345','4567'];
$count = count($m);
$result = 0;
$response =0;
for($i=0;$i<$count; $i++){
if($m[$i]<$n[$i]){
$splitedm = str_split($m[$i],1);
$splitedn = str_split($n[$i],1);
$sCount = strlen($m[$i]);
for($j=0;$j<$sCount;$j++){
for($k=$splitedm[$j]; $k<$splitedn[$j]; $k++){
$result += $response+1;
}
}
}elseif($m[$i]>$n[$i]){
$splitedm = str_split($m[$i],1);
$splitedn = str_split($n[$i],1);
$sCount = strlen($m[$i]);
for($j=0;$j<$sCount;$j++){
for($k=$splitedm[$j]; $k<$splitedn[$j]; $k--){
$result += $response+1;
}
}
}
}
echo $result;
$m and $n having example values which i got in exam that's why i used the same.
step1 : first count no of element in array.
step2 : based on run for loop.
step3 : use if else condition to check which one is greater.
step4 : then split element value in single no (like- 1,2,3,4 for all).
step5 : now it is comparing one to one from $splitedm[$j] and $splitedn[$j]
step6 : consider every positive action as a move and storing in $result.
so that i can get minimum no of moves that can achieve the same value of $n elements.
hope you guys understand now.
This is my opinion to do that.
Happy Coding !!

Load next array item in PHP quiz

I am creating a small PHP quiz and I have a Multidimensional Array set up (which houses my question titles and questions), I then use rand_array to chose one of the arrays and display it into my page. After it has been displayed I use unset($row); to remove it from my Multidimensional Array so that the same question is never shown twice.
There are three buttons (for the three answers) and when that is clicked it will give 0, 10 or 20 points to the user. I have used this to get the points back:
if (isset($_POST["Answer1"])){
$points = $points + 20;
initialQuestions();
}
I run initialQuestions(); again to get the next question but this obviously resets my entire array, how do I make it skip to the next question with the previous item removed from the array eventually leading it to be a blank array?
Any help would be much appreciated.
use array splice instead of unset cause the vallue gets nulled but the key remains
initialQuestions()? And where is Your array?
use initialQuestions($question_array) and return array without current question;
Something like this
$questions = array('your array');
function initialQuestions($questions) {
//get some question
//remove it from array
return $questions;//return this array
}
then
if (isset($_POST["Answer1"])){ $points = $points + 20; $questions = initialQuestions($questions);
or globalize $questions array
function initialQuestions() {
global $questions;
//get some question
//remove it from array
}
But best for me is using $_SESSION to store Your $question array.
you can just randomly pull a question from the all_question array, and save this 'used' question into Session, then doesn't matter what you do in the POST back, the next time when you pull a 'next' question from all_question, you just check it see if it's already stored in the 'used' Session, if so, pull again, if not, you got what you want.
<?php
session_start();
$all_question = array(
//put all your question here...
);
//pull a question out
$new_question = pull_question( $all_question );
//save this question to the 'used' session
$_SESSION['used_question'][] = $new_question;
?>

Categories