开发者

Extract Value from PHP Object

开发者 https://www.devze.com 2023-03-02 13:55 出处:网络
I have been attempting to develop a PHP API for a website. I have followed the tutorials on the Internet that work fine.

I have been attempting to develop a PHP API for a website. I have followed the tutorials on the Internet that work fine.

It works off the following url structure:

http://localhost/mobileapi/search/dostuff/parameter1/parameter2/parameter3/parameter4/json={"name":"jumbo","age":"178","sex":"male"}

Command Object
(
    [Name] => search
    [Function] => dostuff
    [Parameters] => Array
        (
            [0] => parameter1
            [1] => parameter2
            [2] => parameter3
            [3] => parameter4
            [4] => json={"name":"jumbo","age":"178","sex":"male"}
        )

)

What I need to do is access these parameter values, the one I have been attempting first is probably the harder one being the json.

What I have so far is:

    $params[] = $this->Command->getParameters();
    $json = urldecode($params[0][4]);
    $json = str_replace('json=', '', $json);
    $json = json_decode($json);

Providing me with:

stdClass Object
(
    [name] => jumbo
    [age] => 78
    [sex] => male
)

Which still ends up being an object.

My end goal is to be able to receive JSON data to the开发者_如何学Python API and then insert that into the database. I can't for the life of me find out how to take these last object values and store them in variables etc.

Thank you :)


It's very simple - You can access these properties like this:

$params[] = $this->Command->getParameters();
$json = urldecode($params[0][4]);
$json = str_replace('json=', '', $json);
$json = json_decode($json);

$name = $json->name;
$age = $json->age;
$sex = $json->sex;

Is this what You want to find out?

Even the Command parameters can be accessed like this:

$params = $this->Command->parameters;

This is done by the object relation sign '->' that is similar to '.' in Java or .NET and it goes like object->property or parent->child.


Add:

if ($json instanceof stdClass) {
    $json = (array)$json;
}


$json = '{"name":"jumbo","age":"178","sex":"male"}';
$json = (array) json_decode($json);
echo '<pre>';
print_r($json);
echo '</pre>';


I don't exactly understand what you want, but see if this code helps you. I wrote it now. It will build a MySQL query from objects:

   $a = array();
   foreach((array)$json as $key=>$value)
       $a[] = "$key='$value'";
   mysql_query("INSERT INTO sometable SET ".implode(',' $a));

Don't forget to add a sanitize call for the SQL parameters in your real code !!

BTW, if you want json_decode to return an array you can add true as the second parameter:

   $json_array = json_decode($obj, true);
0

精彩评论

暂无评论...
验证码 换一张
取 消