Php:Combine Id and value array
Get the solution ↓↓↓I have two comma delimited lists corresponding to the Ids and values of something returned by a query. I can easily convert each into an array using explode.
My question is how can I convert the two lists into a set of hyperlinks that use one from each as follows:
Ids: 34,23,78
Values: red, blue, green
Links: <a href='get.php?id=34'>red</a> etc.
I can use:
$valuesarray =explode(',',$values);
foreach($valuesarray as $val) {
Echo ....$Val
}
But how do I get the Ids into the link?
Answer
Solution:
Personally, I'd usearray_combine
to combine them into one array:
$arr = array_combine(explode(",",$ids),explode(",",$values));
foreach($arr as $id=>$value) {
...
}
But there are other ways. Such as:
$idarray = explode(",",$ids); $valuesarray = explode(",",$values);
// option 1:
foreach($idarray as $k=>$id) {
$value = $valuesarray[$k];
}
// option 2:
$length = count($idarray);
for( $i=0; $i<$l; $i++) {
$id = $idsarray[$i]; $value = $valuesarray[$i];
}
And so on.
Answer
Solution:
using $key => $value in the for each loop will accomplish this.
foreach($valuesarray as $id => $val) {
echo '<a href="file.php?id=' . $id . '">' . $val . '</a>';
}
Answer
Solution:
If you can assume the count of items is always the same you can just do a regular for loop:
for ($i = 0; $i < count($valuesarray); $i++) {
echo "<a href='get.php?id=" . $idsarray[$i] . "'>" . $valuesarray[$i] . "</a>";
}
Answer
Solution:
You could map them into an array with "id's" as key and "values" as values, like this:
$id_array = explode(',', $ids);
$value_array = explode(',', $values);
$final_array = array();
for ($i=0; $i < count($id_array); $i++) {
$final_array[$id_array[$i]] = $value_array[$i];
}
Note that you may also want to verify that the number of id's matches the number of values before entering the loop.
Answer
Solution:
$ids = '33,22,55';
$values = 'red,yellow,blue';
$ids = explode(',', $ids);
$values = explode(',', $values);
foreach($ids as $key => $value){
echo "<a href='get.php?id=$ids[$key]'>$values[$key]</a><br />";
}
Answer
Solution:
Try this:
$id_arr = explode(',',$ids);
$val_arr = explode(',',$values);
for($i = 0; $i < count($id_arr); $i++)
{
echo '<a href="get.php?id='.$id_arr[$i].'">'.$val_arr[$i].'</a>';
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: git was not found in your path, skipping source download
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.