2

I am having trouble to create an javascript array which appears from an php array. This is how i tried.

My PHP array called $samlet.

This is my output:

    Array ( [0] => Array ( [m_field_id_8] => ) [1] => Array ( [m_field_id_8] => ) [2] => Array ( [m_field_id_8] => 10102a ) [3] => Array ( [m_field_id_8] => 10180a ) [4] => Array ( [m_field_id_8] => 10210a ) [5] => Array ( [m_field_id_8] => 10212a ) [6] => Array ( [m_field_id_8] => 10242a ) [7] => Array ( [m_field_id_8] => 10248a ) [8] => Array ( [m_field_id_8] => 10258a )

I want it to convert to an javascript array.

But before i do that i tried with a mockup javascript array, which works great.

<script>
var availableTags = [
"Test1",
"Test2",
"Test3",
"Test4",
"Test5",
];

now i want to use my php array instead. This is how i tried. But this does not work. Why is this happining?

    <?php 
    foreach($samlet as $category => $value) 
    {
    ?>
    var availableTags = [<?php echo $value['m_field_id_8']; ?>]
    <?php
    }
    ?>
</script>
4
  • What results do you get? Commented Mar 16, 2013 at 13:44
  • var availableTags = [<?php echo $value['m_field_id_8']; ?>]; You need to print or echo the value ? Commented Mar 16, 2013 at 13:45
  • And it looks like instead of var availableTags = [1,2,3], you'll get var availableTags = [1] var availableTags = [2] var availableTags = [3] Commented Mar 16, 2013 at 13:47
  • And then you'll do var availableTags = [<?php echo implode(', ', $value); ?>]; Commented Mar 16, 2013 at 13:47

3 Answers 3

3

You can use json_encode to create JSON array

echo 'var availableTags = ' . json_encode(array_map(function($value) {
   return $value['m_field_id_8'];
}, $samlet));
2
  • I tried this way, but i did not work :/ I just updated my question. Commented Mar 16, 2013 at 14:28
  • @Zaz you don't have assoc array so you don't need to use array_values function. Commented Mar 16, 2013 at 18:39
2

It should be foreach($samletas as $category => $value)

And

var availableTags = [];
availableTags.push(<?php echo $value['m_field_id_8']; ?>);

If $value['m_field_id_8'] is string type quote it like this:

availableTags.push("<?php echo $value['m_field_id_8']; ?>");
1
  • in javascript you will need to do availableTags.push this is only available in php. And quotes need to be inside brakets. Commented Mar 16, 2013 at 13:56
1

Declare an array outside of your loop

var availableTags = [];

Then in your iteration:

availableTags.push(<?php echo $value['m_field_id_8']; ?>);

And add as in your foreach

foreach($samletas as $category => value);
1
  • I also tried this way, but i did not work :/ But i just updated my question Commented Mar 16, 2013 at 14:30

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.