1

With php, I need to convert json arrays into arrays, what should I do, json_encode didn't work for me, thanks in advance for help.

//json sequence

[
  {
   "name":"Menu",
   "sub":
   [
     {
      "name":"Menu 2",
      "url":"menu-2.php"
     }
   ]
  }
]

this way i should do

array(
    'name'  => 'Menu',
    'sub'   => array(
        array(
            'name'  => 'Menu 2',
            'url'   => 'menu-2.php'
        )
    )
)

i am creating json array with this function Do I have to make a change here? I'm not really good in arrays.

<?php
    $connect = new PDO("mysql:host=localhost; dbname=propanel_001", "root", "");
    $parent_category_id = "";
    $query = "SELECT * FROM tb_sayfalar";
    $statement = $connect->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    foreach($result as $row)
    {
        $data = get_node_data($parent_category_id, $connect);
    }
    echo json_encode(array_values($data));
    function get_node_data($parent_category_id, $connect)
    {
        $query = "SELECT * FROM tb_sayfalar WHERE parent_id = '".$parent_category_id."'";
        $statement = $connect->prepare($query);
        $statement->execute();
        $result = $statement->fetchAll();
        $output = array();
        foreach($result as $row)
        {
            $sub_array = array();
            if (array_values(get_node_data($row['id'], $connect))) {
                $sub_array['name'] = $row['page_name']; 
                $sub_array['sub'] = array_values(get_node_data($row['id'], $connect));
            }else{
                $sub_array['name'] = $row['page_name']; 
                $sub_array['url'] = $row['page_url'].".php";
            }
            $output[] = $sub_array;
        }
        return $output;
    }
?>
Redmaster
  • 35
  • 1
  • 7

2 Answers2

2

This is what you need, json_decode($json,true);

<?php
$json = '[{"name":"Menu","sub":[{"name":"Menu 2","url":"menu-2.php"}]}]';
$array = json_decode($json,1);
print_r($array[0]);
?>

DEMO: https://3v4l.org/JZQCn

OR use it as a parsable string representation of a variable with var_export()

<?php
$json = '[{"name":"Menu","sub":[{"name":"Menu 2","url":"menu-2.php"}]}]';
$array = var_export(json_decode($json,1)[0]);
print($array);
?>

DEMO: https://3v4l.org/rLA9R

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
1

You must use json_decode to convert JSON representing Object to Associative array.

Example Code

$resArr = json_decode($response, true);

For more information look at PHP JSON_DECODE

Roshan
  • 786
  • 1
  • 9
  • 20
  • I need to use json_decode when creating json data, do I understand correctly? – Redmaster Feb 06 '19 at 01:32
  • please, no such thing as a json object, or a json array : json is just a string that represents an object. You can (in php) serialize an object or associative array to a `json string` with json_encode , and deserialize a string (decode) into objects or associative arrays. – YvesLeBorg Feb 06 '19 at 01:39