1

Hello I have an array and a foreach loop, which is technically working fine. Here is my code.

foreach ($results as $result) {
    $data['manrat'][] = array(
        'manufacturer' => $result['manufacturer'],
        'mhref'        => $this->url->link('/info', 'manufacturer_id=' . $result['manufacturer_id'])
    );
}

And

<?php foreach($manrat as $manrate) { ?>
    <a href="<?php echo $manrate['mhref']; ?>"><?php echo $manrate['manufacturer'];?> </a>
<?php } ?>

This is give me a result like this:

name1 name2 name3 name4 name5

I would like to store each name to different variables. This is possible?

2
  • 2
    Yes. But what's the logic of it? Do you really need separate variables for whatever you are trying to do? Commented Aug 30, 2016 at 16:03
  • I need to use them later, display in a highchart. I use highchart.js and there I have to set the names for each column. But the names are coming from database. Commented Aug 30, 2016 at 16:12

3 Answers 3

2

I don't quite understand your question properly but if this is what you mean, then here's my answer. You can just store to different variable or an array like names[] by adding the assigning code in your loop like:

<?php
$names = array();
foreach($manrat as $manrate) {
 $names[] = $manrate['manufacturer'];
}
?>

You can then get the names as elements of the array like: $names[0], $names[1], ... etc.

I hope this answered your question.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, maybe my question is not was clear. But this is exactly what I looking for. Thank you!
array_columns() does all that in a single line of code...
0

I would refactor this code into one foreach loop like this:

$anchors = '';

foreach ($results as $result) {
    $anchors .= '<a href="' . $this->url->link('/info', 'manufacturer_id=' . $result['manufacturer_id']) . '">' . $result['manufacturer'] . '</a>';
}

and on your actual HTML output page:

<?php echo $anchors ?>

Comments

0

use implode and if you want turn String to Array use explode

$array_to_string = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
$store_to_string =  implode(',',$array_to_string ); // a,b,c,d,e,f,g

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.