2017-04-20 4 views
1

내 팀원 중 한 명이이 객체를 MySQL 데이터베이스에 저장했습니다. 개체 속성 값을 추출해야합니다. PHP를 사용하여 MySQL에서 가져 오려고 할 때 문자열로 가져옵니다. 그리고 PHP는 substr() 기능을 사용하는 아이디어를 제외하고 부동산에 직접 액세스 할 운이 없습니다.print_r 배열을 PHP에서 json으로 json으로 변환

데이터베이스에 저장된 아래 문자열을 다시 개체로 변환하여 해당 속성에 액세스 할 수있는 옵션이 있습니까?

stdClass Object 
(
[status] => 0 
[environment] => Sandbox 
[receipt] => stdClass Object 
    (
     [quantity] => 1 
     [expires_date] => 2017-04-18 08:56:57 Etc/GMT 
     [is_trial_period] => false 
     [purchase_date] => 2017-04-18 08:51:57 Etc/GMT 
     [product_id] => com.1monthAuto.baseball 
     [original_purchase_date_pst] => 2017-04-18 01:51:58 America/Los_Angeles 
     [original_purchase_date_ms] => 1492505518000 
     [web_order_line_item_id] => 1000000034854560 
     [original_purchase_date] => 2017-04-18 08:51:58 Etc/GMT 
    ) 

[latest_receipt] => MIIT6wYJKoZIhvcNAQcCoIIT3DCCE9gC 
) 
+1

액세스 할 속성은 무엇입니까? –

+0

'latest_receipt'에 접속하고 싶습니다. –

+3

데이터베이스에 객체를 저장하는 것은 저에게 끔찍한 디자인 패턴처럼 들립니다. 이렇게하면 이런 문제가 발생할 수 있습니다. – Qirel

답변

1

이 정보는 도움이 될 것입니다.

정규식 :/latest_receipt\]\s*=>\s*\K[^\s\)]+/

latest_receipt\]\s*=>\s*

\K이 모든 공간 (\s) 및 )

제외 일치 이전 매치

[^\s\)]+를 재설정 latest_receipt] 공백 => 공백

일치

(210)

<?php 

ini_set('display_errors', 1); 
$string='stdClass Object 
(
[status] => 0 
[environment] => Sandbox 
[receipt] => stdClass Object 
    (
     [quantity] => 1 
     [expires_date] => 2017-04-18 08:56:57 Etc/GMT 
     [is_trial_period] => false 
     [purchase_date] => 2017-04-18 08:51:57 Etc/GMT 
     [product_id] => com.1monthAuto.baseball 
     [original_purchase_date_pst] => 2017-04-18 01:51:58 America/Los_Angeles 
     [original_purchase_date_ms] => 1492505518000 
     [web_order_line_item_id] => 1000000034854560 
     [original_purchase_date] => 2017-04-18 08:51:58 Etc/GMT 
    ) 

[latest_receipt] => MIIT6wYJKoZIhvcNAQcCoIIT3DCCE9gC 
)'; 
preg_match("/latest_receipt\]\s*=>\s*\K[^\s\)]+/", $string,$matches); 
print_r($matches); 

해결 방법 2 :or you can Try this library //이 솔루션이 반드시 jsonprint_r을 변환하고, 작동합니다.

Try this code snippet here (Copy paste below code and check)

<?php 
ini_set('display_errors', 1); 
/** 
* @author Sahil Gulati <[email protected]> 
*/ 
echo printr_source_to_json(
     print_r(
       array("Name"=>"Sahil Gulati", 
         "Education"=>array(
          "From"=>array(
           "DU"=>array(
            "Course"=>"B.Sc. (Hons.) Computer Science.") 
          ) 
         ) 
        ) 
       , true 
       ) 
     ); 
/** 
* This function will convert output string of `print_r($array)` to `json string` 
* @note Exceptions are always there i tried myself best to get it done. Here $array can be array of arrays or arrays of objects or both 
* @param String $string This will contain the output of `print_r($array)` (which user will get from ctrl+u of browser), 
* @return String 
*/ 
function printr_source_to_json($string) 
{ 
    /** 
    *replacing `stdClass Objects (` to `{` 
    */ 
    $string = preg_replace("/stdClass Object\s*\(/s", '{ ', $string); 

    /** 
    *replacing `Array (` to `{` 
    */ 
    $string = preg_replace("/Array\s*\(/s", '{ ', $string); 
    /** 
    *replacing `)\n` to `},\n` 
    * @note This might append , at the last of string as well 
    * which we will trim later on. 
    */ 
    $string = preg_replace("/\)\n/", "},\n", $string); 

    /** 
    *replacing `)` to `}` at the last of string 
    */ 
    $string = preg_replace("/\)$/", '}', $string); 
    /** 
    *replacing `[ somevalue ]` to "somevalue" 
    */ 
    $string = preg_replace("/\[\s*([^\s\]]+)\s*\](?=\s*\=>)/", '"\1" ', $string); 
    /** 
    * replacing `=> {` to `: {` 
    */ 
    $string = preg_replace("/=>\s*{/", ': {', $string); 
    /** 
    * replacing empty last values of array special case `=> \n }` to : "" \n 
    */ 
    $string = preg_replace("/=>\s*[\n\s]*\}/s", ":\"\"\n}", $string); 

    /** 
    * replacing `=> somevalue` to `: "somevalue",` 
    */ 
    $string = preg_replace("/=>\s*([^\n\"]*)/", ':"\1",', $string); 
    /** 
    * replacing last mistakes `, }` to `}` 
    */ 
    $string = preg_replace("/,\s*}/s", '}', $string); 
    /** 
    * replacing `} ,` at the end to `}` 
    */ 
    return $string = preg_replace("/}\s*,$/s", '}', $string); 
} 
+0

+1이 값을 추출하는 것이 좋습니다.이 문자열을 객체로 만들 수있는 옵션이 있습니까? 그래서 다른 속성 값도 추출 할 수 있습니까? –

+0

@ArunJain 이걸 잘 살펴 보도록하겠습니다. –

+0

@ArunJain 나는 당신에게 도움이 될 것이라는 희망을 게시 할 새로운 솔루션을 만들었습니다. –

0

문자열로 latest_receipt 콘텐츠를 가지고 정규식과 않는 str_replace를 사용 :

$dictionary="stdClass Object 
    (
    [status] => 0 
    [environment] => Sandbox 
    [receipt] => stdClass Object 
     (
      [quantity] => 1 
      [expires_date] => 2017-04-18 08:56:57 Etc/GMT 
      [is_trial_period] => false 
      [purchase_date] => 2017-04-18 08:51:57 Etc/GMT 
      [product_id] => com.1monthAuto.baseball 
      [original_purchase_date_pst] => 2017-04-18 01:51:58 America/Los_Angeles 
      [original_purchase_date_ms] => 1492505518000 
      [web_order_line_item_id] => 1000000034854560 
      original_purchase_date] => 2017-04-18 08:51:58 Etc/GMT 
     ) 

    [latest_receipt] => MIIT6wYJKoZIhvcNAQcCoIIT3DCCE9gC 
    )"; 
preg_match('/.*\[latest_receipt\].*$/m', $dictionary, $matches); 
$receipt = str_replace('[latest_receipt] => ', '', $matches[0]); 
echo $receipt; 

당신은 그 기능하고 추출하는 변수로 latest_receipt 대체 할 수 있습니다 당신의 다른 데이터.

하지만 실제로이 데이터를 json 개체로 저장하거나이 데이터를 저장할 새 열을 만드는 것이 좋습니다.

관련 문제