2012-06-27 6 views
2

저는 프로젝트를 진행 중이며, 저를 곤혹스럽게 한 문제를 발견했습니다. 아래 코드는 작동하는지 확인하기위한 클래스 파일과 테스트 페이지입니다. 사이트를 프로그래밍하는 다른 사용자를위한 것입니다. 그렇지 않으면 JSON 출력을 다르게 코딩합니다. 기본적으로 데이터베이스를 구현하는 사람은 데이터베이스에서 여러 데이터 (아래)를 가져 와서 반복하고 각 결과에 대한 클래스 객체를 인스턴스화하고 각 인스턴스를 배열에 연결 한 다음 배열을 printJson 함수에 전달해야합니다 그러면 JSON 문자열이 인쇄됩니다. 여기에 내가 무엇을 가지고 :배열의 클래스 인스턴스에 액세스하기

Results.php

<?php 

    class Result 
    { 
     public $Category = NULL; 
     public $Title = NULL; 
     public $Price = NULL; 

     public function __construct($category, $title, $price) 
     { 
      $this->Category = $category; 
      $this->Title = $title; 
      $this->Price = $price; 
     } 

     public static function printJson($arrayOfResults) 
     { 
      $output = '{"results": ['; 

      foreach ($arrayOfResults as $result) 
      { 
       $output += '{"category": "' . $result->Category . '",'; 
       $output += '"title": "' . $result->Title . '",'; 
       $output += '"price": "' . $result->Price . '",'; 
       $output += '},'; 
      } 

      $output = substr($output, 0, -1); 
      $output += ']}'; 

      return $output; 
     } 
    } 

    ?> 

getResults.php

<?php 

    require_once('Result.php'); 

    $res1 = new Result('food', 'Chicken Fingers', 5.95); 
    $res2 = new Result('food', 'Hamburger', 5.95); 
    $res3 = new Result('drink', 'Coke', 1); 
    $res4 = new Result('drink', 'Coffee', 2); 
    $res5 = new Result('food', 'Cheeseburger', 6.95); 

    $x = $_GET['x']; 

    if ($x == 1) 
    { 
     $array = array($res1); 
     echo Result::printJson($array); 
    } 
    if ($x == 2) 
    { 
     $array = array($res1, $res2); 
     echo Result::printJson($array); 
    } 
    if ($x == 3) 
    { 
     $array = array($res1, $res2, $res3); 
     echo Result::printJson($array); 
    } 
    if ($x == 5) 
    { 
     $array = array($res1, $res2, $res3, $res4, $res5); 
     echo Result::printJson($array); 
    } 

    ?> 

을 내가 getResults.php X = 5에 가면 그 결과가, 그것은 $를 반환합니다 res1 ~ res5 (다시 테스트하기 만하면됩니다. 프로덕션 환경에서는 JSON으로 포맷하지 않습니다.) 바로 지금, 나는 '0'출력을 얻었고, 나는 왜 인생을 이해할 수 없습니까? 내 foreach 루프가 제대로 작성되지 않을 수 있습니까? 제발, 당신이 제공 할 수있는 어떤 도움도 끝내 줄 것입니다! 당신이 연결보다는 .에 대한 +를 사용하고 있기 때문에

+3

직접 JSON 문자열을 작성하지 마십시오. 거기에 [json_encode] (http://php.net/json_encode)가 있습니다. – cmbuckley

+0

또한이 경우에는 ['JsonSerializable'] (http://php.net/JsonSerializable) 인터페이스 만 고려하십시오. – hakre

답변

2

그건 :

$output .= '{"category": "' . $result->Category . '",'; 
$output .= '"title": "' . $result->Title . '",'; 
$output .= '"price": "' . $result->Price . '",'; 
$output .= '},'; 

하지만 당신이 정말로 JSON 자신을 구성하지 않아야은 무효 JSON을 위해 만드는 오류의 번호로 연결로, (쉼표 등을 후행). 대신 다음과 같이 사용하십시오.

public static function printJson(array $arrayOfResults) 
{ 
    $results['results'] = array_map('get_object_vars', $arrayOfResults); 

    return json_encode($results); 
} 
+1

의견에서 귀하의 원래 제안은이 답변보다 훨씬 낫습니다. 그래서 당신은 대답에 그것을 포함시키기를 원할 것입니다. –

+0

그것을 추가하는 과정에있었습니다 :-) – cmbuckley

+0

@cbuckley : 도움이 필요한 경우 조금 대답을 편집했습니다. 이것을 봐주세요. – hakre

관련 문제