Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert jQuery Array string to PHP Array

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.

like image 501
Grozav Alex Ioan Avatar asked Dec 13 '25 13:12

Grozav Alex Ioan


1 Answers

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
like image 122
Shankar Narayana Damodaran Avatar answered Dec 16 '25 04:12

Shankar Narayana Damodaran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!