3

Hello Stack Overflow,
This is my first post and I have a problem I need to parse this text and turn it into an array (its from a database).

"TableToKeyValues"
{
    "inventory"
    {
        "slot2"
        {
            "amount"        "10"
            "item"      "wood_plank"
        }
        "slot1"
        {
            "amount"        "10"
            "item"      "metal"
        }
        "slot3"
        {
            "amount"        "10"
            "item"      "plastic"
        }
    }
}

Thanks rtm516.

2 Answers 2

3

I worked out how to do it by formatting it into json useing str_replace alot of times.

$inv = preg_replace( "/\r|\n/", "", $inv);
$inv = str_replace('}', '},', $inv);
$inv = str_replace('"       "', '":"', $inv);
$inv = str_replace('"           "', '","', $inv);
$inv = str_replace('"       {', '":{', $inv);
$inv = str_replace('"   {', '":{', $inv);
$inv = str_replace('"{', '":{', $inv);
$inv = trim(preg_replace('/\t+/', '', $inv));
$inv = str_replace('},}', '}}', $inv);
$inv = str_replace('},},', '}}', $inv);
$inv = str_replace('"TableToKeyValues":', '', $inv);
$inv = json_decode($inv, true);

Edit: $inv is the value from the database.

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

Comments

0

If you want that to be converted into array use json_decode

$arr = json_decode($dataComingFromDBHERE, true);
print_r($arr);

2 Comments

I thought it's a json. Where did the data coming from? Before inserting in the database.
A game called garrys mod using the lua function util.TableToKeyValues

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.