3

First of all, I gotta say I'm pretty new to PHP and I'm trying to get a PHP object on which I can use foreach.

The following string is passed through $.ajax(); I'm trying to turn the following string:

$menu = "[
 {"title" : TEST1, "href" : #},
 {"title" : TEST2, "href" : QWERTY},
 {"title" : TEST3, "href" : QWERTY, "active" : 1}
]"

into and php object on which I can use a foreach loop:

foreach($menu as $li){
    echo $li['title'];
}

Am I using the optimal solution for creating the menu items or should I be following another format?

Thank you very much in advance!

Best regards, Alex G.

2 Answers 2

6

That's a JSON format.. and it is broken.. Fix your JSON data as shown and loop using a foreach

PHP

<?php
$menu = '[{"title" : "TEST1", "href" : "#"},
 {"title" : "TEST2", "href" : "QWERTY"},
 {"title" : "TEST3", "href" : "QWERTY", "active" : 1}]';

foreach(json_decode($menu,true) as $k=>$arr)
{
    echo $arr['title']."<br>";
}

OUTPUT :

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

1 Comment

I tried json_decode already and it wasn't working. Thank you very much, putting the QUOTES seems to have fixed it.
1

Try json_decode function

<?php

       $menu = '[
 {"title" : TEST1, "href" : #},
 {"title" : TEST2, "href" : QWERTY},
 {"title" : TEST3, "href" : QWERTY, "active" : 1}
]';
    $test=json_decode($menu );
   print_r($test);
   foreach($test as $ts)
   {
       echo $ts['title'];
       echo "<br>";
    }
 ?>

4 Comments

Should I be setting TEST1, TEST2, etc. as the "TEST1" string in jquery?
@GrozavAlexIoan Look that string is in JSON format.
You used double quotes without character escape
@Let'sCode :- Hey that string is broken. refer Shankar Damodaran's answer.

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.