2014-03-25 3 views
1

"IT/Internet/Web Development/Ajax"형식의 문자열이 있습니다. 나는 그것을 구문 분석 PHP 함수를 만들려고 내가 함수를 작성하는 문제가 그렇게하는 데JSON 객체 만들기

[{ 
    "name": "IT", 
    "subcategories":[ 
    { 
    "name": "Internet", 
     "subcategories" : [ 
     { 
     "name": "Web Development", 
     "subcategories" : [ 
     { 
     "name":"Ajax" 
      }]}]}] 

같은 JSON 객체를 생성하고있다. 이것은 내가 지금까지 가지고있는 것이다.

$category = "IT /Internet /Web Development"; 
$categoryarray = split("\/", $category); 
$categoryLength = count($categoryarray); 
$subcategory_collection = array(); 

$lastCategory = array("name"=>$categoryarray[$categoryLength-1]); 
array_push($subcategory_collection, $lastCategory); 

for($i=$categoryLength-2; $i>=0; $i--) { 
    $subcategory = array("name" => $categoryarray[$i], "subcategories" => $subcategory_collection); 
    array_push($subcategory_collection, $subcategory); 
} 

이것은 원하는 출력을 생성하지 않습니다. "parent/child/grandchild/great grandchild"의 형식으로 제공되는 문자열을 구문 분석하여 JSON 객체로 만들 수있게하려고합니다. 아무도 올바른 방향으로 나를 안내 할 수 있다면 크게 환영 할 것입니다.

+0

가능한 중복 [JSON 객체에게 올바른 방법을 만듭니다] (http://stackoverflow.com/questions/3281354/create-json-object-the-correct-way) –

답변

1

어쩌면 올바른 접근 방법 일 수 있습니다. 가장 깊은 항목부터 시작하여 각 항목에 부모를 추가했습니다. 이유는 모르겠지만 더 쉽다고 생각했습니다. 다른 것을 시도하지 않았습니다. ;)

<?php 
$input = "IT/Internet/Web Development"; 
$items = explode("/", $input); 

$parent = new StdClass(); 
while (count($items)) 
{ 
    $item = array_pop($items); 
    $object = $parent; 
    $object->name = $item; 
    $parent = new StdClass(); 
    $parent->name = ''; 
    $parent->subcategories = array($object); 
} 

echo json_encode(array($object)); 

감사합니다. 한편, 나는 다른 방향으로 노력했다. 루프 자체는 더 쉬울 것이라고 생각하지만 루트 객체를 기억해야하므로 추가 코드가 추가됩니다. 결국에는 큰 차이가 없지만 순서를 뒤집는 것에 대한 내 직감이 옳았다 고 생각합니다. 의

<?php 
$input = "IT/Internet/Web Development"; 
$items = explode("/", $input); 

$parent = null; 
$firstObject = null; 
while (count($items)) 
{ 
    $object = new StdClass(); 
    $item = array_shift($items); 
    $object->name = $item; 
    if ($parent) 
    $parent->subcategories = array($object); 
    else 
    $firstObject = $object; 

    $parent = $object; 
} 

echo json_encode(array($firstObject)); 
+0

는 도움 Golez 주셔서 감사합니다 . 이것은 매우 도움이되었습니다. – aafonso1991

+0

예. 처음 접근법이 더 좋았습니다. 그 이유는 단지 청소기 때문 이었지만 둘 다 작업을 완료했기 때문입니다. 다시 한번 고마워요. Golez – aafonso1991

+0

검색상의 이유로 루트를 추적해야하기 때문에 실제로 두 번째 글자로 끝납니다. – aafonso1991