2013-10-10 15 views
0

如何將stdClass對象的名稱導入數據庫?PHP/JSON - 如何導入stdClass對象的名稱?

JSON對象包含:

[items] => stdClass Object 
        ( 
    [bigitems] => stdClass Object 
        (
         [nameitem1] => stdClass Object 
          (
           [height] => 100 
           [width] => 137 
      ) 
      [nameitem2] => stdClass Object 
          (
           [height] => 506 
           [width] => 678 
      ) 
      [nameitem3] => stdClass Object 
          (
           [height] => 330 
           [width] => 845 
      ) 
      [nameitem3] => stdClass Object 
          (
           [height] => 793 
           [width] => 788 
      ) 
     ) 
) 

我想存儲到數據庫中唯一的價值nameitem1 - nameitem4

Nameitems是例如 - 盒,箱 - 不同的字沒有數值範圍 Bigitems是一個數字

[items] => stdClass Object 
        ( 
    [4856985254] => stdClass Object 
        (
         [box] => stdClass Object 
          (
           [height] => 100 
           [width] => 137 
      ) 
      [case] => stdClass Object 
          (
           [height] => 506 
           [width] => 678 
      ) 
      [paper] => stdClass Object 
          (
           [height] => 330 
           [width] => 845 
      ) 
     ) 

對於此操作我嘗試使用此腳本。腳本工作,但缺少商家部分

function wwwResponse($url, $isUrl = true) 
{ 
    if ($isUrl && !ini_get('allow_url_fopen')) { 
    throw new Exception('allow_url_fopen = Off'); 
    } 

    $content = file_get_contents($url); 
    if ($isUrl) { 
    $status_code = substr($http_response_header[0], 9, 3); 
    if ($status_code != 200) { 
     throw new Exception('Got status code ' . $status_code . ' expected 200'); 
    } 
    } 

    $json = json_decode($content); 
    if (!$json) { 
    throw new Exception('Response contained an invalid JSON response'); 
    } 

    if ($json->status != 'ok') { 
    throw new Exception($json->status_code); 
    } 

    return $json; 
} 

// --------------------------DB------------------------------- 
mysql_connect("localhost", "baze", "xxxxxxx"); 
mysql_select_db("baze"); 
//------------------------------------------------------------ 

    try { 
    $json = wwwResponse($url); 
     print_r ($json); 
    } 
    catch (Exception $e) { 
    echo $e->getMessage(); 
} 
echo "<pre>\n"; 
} 

感謝您的幫助

回答

1
$items = json_decode(json_encode($obj->items), true); 
$names = array_keys((Array) $items['4856985254']); 

// will return Array("nameitem1","nameitem2","nameitem3") 
+0

這不是工作,因爲大項目是一個數字。 – Hunt3r

+0

@ Hunt3r請檢查我的更新 – Peter

+0

有錯誤:注意:未定義的索引:4856985254 – Hunt3r

0
$vars = get_object_vars($items->bigitems); 
foreach ($vars as $key => $value) 
... insert $key .... 
1

如果它可以幫助你可以解碼JSON這種方式來獲得一個數組,而不是性病對象:

$result = json_decode($json, TRUE); 

無論如何你可以這樣做:

foreach ($data as $d) { 
    foreach ($d as $actual) { 
     //echo stuff here 

    } 
}