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 8 years ago.
Improve this question
I have two lists of words in two arrays
first array
Array
(
[0] => make
[1] => break
[2] => buy
)
second array
Array
(
[0] => home
[1] => car
[2] => bike
)
and I want to display all possible combinations but make sure the first array is always the first word and 2nd array is always the second word:
The above two arrays should display the following list:
make home
make car
make bike
break home
break car
break bike
buy home
buy car
buy bike
Thank you in advance.
Hi Saikios,
thanks for your reply.
This is what I have which seems very similar to what you have posted:
$list1 = array("make","break","buy");
$list2 = array("home","car","bike");
for($a=0; $a<3; $a++){
for($b=0; $b<3; $b++){
echo($list1[$a].$list2[$b]);
echo("<br />");
}
}
Just was wondering if there is a better way. Both of my lists have about 200 words.
For a correct answer I would need to know what you are trying or how,
but a solution for that problem is as simple as
<?php
$array1 = array("make", "break", "buy");
$array2 = array("home", "car", "bike");
foreach ($array1 as $i => $value) {
foreach ($array2 as $j => $value2) {
echo $value.' '.$value2.'<br />';
}
}
?>
foreach($firstarray as $f)
{
foreach($secondarray as $s)
{
echo $f.' '.$s;
}
}
To make sure the first array is always the first word we use it as the primary loop. In essence we are iterating through each item and for each item we find in the array we are then looping through the second array so it creates all the word combinations for each item in the first array.
This example is more efficient that the previously chosen answer since pulling the array key out of each item is not needed and therefore not the most efficient answer to the question.
Related
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 1 year ago.
Improve this question
I am trying to display the results of a php for each loop in decending order, from reading a few similar questions here I have worked out I need to put the results of of the loop into an array then sort that, I have attempted to do that with the following code and getting a black page for the result..
$sql=mysqli_query($conn,"SELECT * FROM `live`");
/*every time it fetches the row, adds it to array...*/
while($liveuserscores[]=mysqli_fetch_array($sql, MYSQLI_ASSOC));
//Delete first line
array_pop($liveuserscores);
//echo '<hr><pre>'; print_r($liveuserscores); echo '</pre><hr>';
$sortedarr = [];
foreach ($liveuserscores as $user) {
$userpoints = $user['name'].": ".number_format($user['q1points']+$user['q2points']+$user['q3points']+$user['q4points']+$user['q5points']+$user['q6points']+$user['q7points']+$user['q8points']+$user['q9points']+$user['q10points']+$user['q11points']+$user['q12points']+$user['q13points']+$user['q14points']+$user['q15points']+$user['q16points']+$user['q17points']+$user['q18points']+$user['q19points']+$user['q20points']+$user['q21points']+$user['q22points']+$user['q23points']+$user['q24points']+$user['q25points']+$user['q26points']+$user['q27points']+$user['q28points']+$user['q29points']+$user['q30points']+$user['q31points']+$user['q32points']+$user['q33points']+$user['q34points']+$user['q35points']+$user['q36points']+$user['q37points']+$user['q38points']+$user['q39points']+$user['q40points'])."<br>";
$sortedarr = [] = $userpoints;
}
sort($sortedarr);
echo '<hr><pre>'; print_r($sortedarr); echo '</pre><hr>';
I also have
error_reporting(E_ALL);
ini_set('display_errors', '1');
in the code but getting no error messages.
a sample of print_r($liveuserscores); (with pre tags) is..
Array
(
[0] => Array
(
[ID] => 56
[name] => Glen
[datetime] => Tuesday 02nd Nov 21 21:26pm
[q1seen] => YES
[q1pickedans] => 2
[q1timetoans] => 2.375
[q1points] => 8
[q2seen] => YES
[q2pickedans] => 3
[q2timetoans] => 3.363
[q2points] => 7
)
)
I can get just the sum of users scores to display with this code...
$sql=mysqli_query($conn,"SELECT * FROM `live` ORDER BY name DESC");
/*every time it fetches the row, adds it to array...*/
while($liveuserscores[]=mysqli_fetch_array($sql, MYSQLI_ASSOC));
//Delete first line
array_pop($liveuserscores);
//echo '<hr><pre>'; print_r($liveuserscores); echo '</pre><hr>';
foreach ($liveuserscores as $user) {
echo $user['name'].": ".number_format($user['q1points']+$user['q2points']+$user['q3points']+$user['q4points']+$user['q5points']+$user['q6points']+$user['q7points']+$user['q8points']+$user['q9points']+$user['q10points']+$user['q11points']+$user['q12points']+$user['q13points']+$user['q14points']+$user['q15points']+$user['q16points']+$user['q17points']+$user['q18points']+$user['q19points']+$user['q20points']+$user['q21points']+$user['q22points']+$user['q23points']+$user['q24points']+$user['q25points']+$user['q26points']+$user['q27points']+$user['q28points']+$user['q29points']+$user['q30points']+$user['q31points']+$user['q32points']+$user['q33points']+$user['q34points']+$user['q35points']+$user['q36points']+$user['q37points']+$user['q38points']+$user['q39points']+$user['q40points'])."<br>";
}
But the order is not sorted by largest score at the top.
I see few problem with this code
first
array_pop($liveuserscores);
is removing the item you have just fetched from your array so you always working with a empty array, also array_pop remove the last element and not the first.
Also I-m pretty sure that this $sortedarr = [] = $userpoints; will reset $sortedarr to an empty array
Also sort function doesn't know how to sort an associative array, you have to define a sorting function using usort.
If I understood your question correctly you want to sort the results by the score.
And the score is the sum of few different column
You can change the query like this:
SELECT *,
q1points + q2points + ... + q40points AS score
FROM live
ORDER BY score DESC
So now you don't have to sort it manually
you can do
$sortedarr = mysqli_fetch_all($sql, MYSQLI_ASSOC);
echo '<hr><pre>'; print_r($sortedarr); echo '</pre><hr>';
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
I have a line of code to get attributes :
$attributes = $as->getAttributes();
When i use print_r
$results = print_r($attributes);
This is what i get :
Array
(
[http://schemas.microsoft.com/2012/12/certificatecontext/extension/subjectkeyidentifier] => Array
(
[0] => username
)
[http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress] => Array
(
[0] => email#mail.com
)
[http://schemas.xmlsoap.org/claims/CommonName] => Array
(
[0] => User lastname
)
[http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn] => Array
(
[0] => email#mail.com
)
[uid] => Array
(
[0] => user
)
)
How can i display those results with a foreach ?
To get all the informations you can use
foreach($attributes as $url=>$info)
{
echo $url; //example : http://schemas.microsoft.com/2012/12/certificatecontext/extension/subjectkeyidentifier
foreach($info as $key=>$attr)
{
echo $key; //example : 0
echo $attr; //example : username
}
}
Per your answers to the comments, you want to be able to format each row differently. Therefore, you could do something like the following:
<?php
foreach($attributes as $key => $value){
echo $key; // the key of the array
echo $value; // the value of the array row
echo '<br />'; // if you want a new line
}
However, if you want a common format, such as a list, you could use implode to do it for you (docs).
<?php
echo '<ul><li>'; // Open list and add first open tag
echo implode('</li><li>', $attributes);
echo '</li></ul>'; //Close last item and list element
And this would generate an HTML formatted list of the elements, though you certainly could do any delimiter that worked for your project.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a code to modify the data that comes up from external API. However, I didn't like my code. I believe that there is a shorter way to do.
let me explain the flow:
I request to an api endpoint to get currency short codes. I mean $results contains these:
[0] => EURUSD
[1] => USDTRY
etc...
I want to save these as EUR, USD, TRY. I used str_split to do this. Also, I used array_unique to remove the same values.
Right now, my array contains this.
[0] => EUR
[3] => USD
[5] => TRY
It's not enough for me. I need to change keys according to my database structure.
My table contains: id, name, created
I have to rename each key as name. (btw I use Phnix to migrate and seeding)
$results = json_decode($httpResponse->getBody());
$data = [];
$prepared = [];
foreach ($results as $key => $item) {
$data = array_merge($data, str_split($item, 3));
}
$data = array_unique($data);
foreach ($data as $key => $item) {
array_push($prepared, ['name' => $item]);
}
$currency = $this->table('currency');
$currency->truncate();
$currency->insert($prepared)->save();
Do you have any clue for the best way?
in your code you make a lot of useless operation: considering that the lenght of the string is always 3 char you can simply use substr to obtain the currency code and use the currency code as key to make your array "unique" (if the same currency is added more than once, will "override" the previous one, whithout affecting the final result).
$results = json_decode($httpResponse->getBody());
$prepared = [];
foreach ($results as $item) {
$itemName = substr($item,0,3);
$prepared[$itemName] = ['name' => $itemName];
}
$currency = $this->table('currency');
$currency->truncate();
$currency->insert($prepared)->save();
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 6 years ago.
Improve this question
I have an array with different extension's values, Now i want check whether '.csv' is IN this Array or not . If it is then whats the name.
Ex: - Array
(
[0] => xyz.mp4
[1] => bulk_sample.csv
[2] => abc.avi
[3] => pqr.3gp
)
Here 'abc.csv' is available in array. and name should be in $name='abc.csv';
Simple "one-line" solution using preg_grep function:
$names = preg_grep("/\.csv$/i", $val);
print_r($names);
The output:
Array
(
[3] => abc.csv
)
Note, that hypothetically there could be multiple .csv items
Try this code :
In this foreach loop is checking for sub string which is .csv for all elements in array.
<?php
$array =array('test.mp4','abc.avi','xyz.3gp','abc.csv');
$flag=false;
$filename="";
foreach($array as $check) {
$place = strpos($check, ".csv");
if ($place>0) {
$flag=true;
$filename=$check;
break;
} else {
$flag=false;
}
}
if($flag){
echo "File Name:".$filename;
}else{
echo "not found any .csv in array"."<br>";
}
?>
Note: it will return first found name with .csv extension.
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 7 years ago.
Improve this question
From a mySQL row I get the below from column coop as appeared (with commas)
1,2,6,27
My question is how can I have something like
for
as numbers as the column
do the loop {
{
Assuming you have the values stored in a string, let's call it $dbValue, you can split that string into an array:
$values = explode(",", $dbValue);
Then just loop over that array:
foreach ($values as $value) {
// do something with each value
}
As an aside... Storing delimited values in a single database field is very often a bad idea. Each database field should contain one discrete value. If multiple values are needed, you'd create a separate table with a many-to-one relationship.
seems foreach
$tmp = explode(',', $yourvalue) // $yourvalue = '1,2,6,27'
foreach ( $tmp as $key => $value ) {
echo $value;
}