0

hello i am trying to figure out how i would ago about pulling information from a database in php and json_encoding it ito a JavaScript object that contains several JavaScript arrays that themselves have children objects and arrays. below is the JavaScript i need. ive been playing with embedding arrays into php objects but cant seem to get it to come our correctly.

self.navigation = [
    {
        menutext:"Home",
        url:"/"
    },
    {
        menutext:"About",
        url: "#/about",
        submenu:[
        {
            menutext:"Pricing",
        url: "/pricing"
        }
        ]
    }
    ];
1
  • what have you tried? post php code. json_encode() will probably do what you need, might need to tweak the options a bit. Commented Jan 19, 2015 at 6:04

1 Answer 1

1
<script type="text/javascript">
 var jsObject = <?php echo json_encode($phparray); ?>;
</script>

pretty self-explanatory i think, if you need the object a specific way it's about how you format your php array itself.

To get arrays within objects you use the object key and set it to an array like so:

$phpArray = array(
        'magic' => array('elmo')
);

json_encoded an array will be within the "magic" object. In order to get the parent item as an array with objects inside i would just fudge it in the variable setting itself like so:

<script type="text/javascript">
 var jsObject = [<?php echo json_encode($phparray); ?>];
</script>

To get submenu into array have you tried the following:

$phpArray = array(
'menutext' => 'About',
'url' => '#/about',
'submenu' => array(
    array(
    'menutext' => 'Pricing',
    'url' => '/pricing')
)
);

Bit unintuitive I know. Actually to get exactly what you want without fudging it would be:

$phpArray = array(
array(
'menutext' => 'Home'
),
array(
'menutext' => 'About',
'url' => '#/about',
'submenu' => array(
    array('menutext' => 'Pricing',
    'url'=> '/pricing')
)
)
);
Sign up to request clarification or add additional context in comments.

3 Comments

im sure this is the right anwser but having troubles getting it to make the submenu into an actual array, seems to be the only way i can get angular to read it
I've edited my answer, should help you out more now ;)
amazing, missing that second array call lol i have beaten my head against the wall for days.... made me realize i need to learn more about javascript lol

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.