2013-07-28 6 views
1

PHP에서 다차원 배열을 가지고 있는데, 어떤 규칙에 따라 조작하고 싶습니다.PHP에서 다차원 배열의 내용이 변경 되었습니까?

입력 - 배열 : (변수가 JSON로 인쇄)

[ 
    { 
     "meta":{ 
       "title": "Adressdata", 
       "name": "adress" 
     },  
     "data":{ 
      "desc":{ "tooltip": "text", 
         "maxlength": "100" 
       }, 
      "line1":{ "tooltip": "Recipient", 
         "maxlength": "40" 
       } 
    } 
] 

규칙 :

{ 
    "0>meta>title": "Companyaddress", 
    "0>data>desc": { 
     "tooltip": "Another Text", 
     "maxLength": "150" 
    } 
} 

(2 규칙이 인덱스는 입력에서 어떤 필드를 설명합니다 - 배열을 변경해야하며 값에 삽입 할 데이터가 들어 있습니다. 두 번째 규칙은 객체를 삽입하려고합니다.)

문제 :

나는 규칙에 따라 입력 배열의 내용을 변경하려면,하지만 난 그 일에 투쟁.

는 여기에 내가 이미 가지고있는 PHP 코드입니다 :

<?php 
    $input = json_decode(file_get_contents("inputData.json"),true); 
    $rules = json_decode(file_get_contents("rules.json"),true); 

    foreach ($rules as $target => $replacement) {  
     //rule: "0>meta>title": "newTitle" 

     $node = $input; 
     foreach (explode(">",$target) as $index) { 
      $node = $node[$index]; 
     } 

     $node = $replacement; //replace doesn't work  
    } 

    echo "Result-Array: "; 
    print_r($input); 
?> 

모든 것은 내가 값을 변경할 수 있다는 점을 제외에서 작동합니다. 왜? 왜냐하면 매번 $ node-Variable을 설정하기 때문에 새로운 변수를 만듭니다. 그리고 $ node의 내용 만 변경하고 $ input의 내용은 변경하지 않습니다.

그래서 나는 참조 사용하려고 - 중 하나가 작동하지 않습니다 이 코드에 2 $ 노드 라인을 변경할 경우 : 때문에,

$node = &$input; 
[...] 
$node = &$node[$keys[$i]]; //go to child-node 

그러나이 작동하지 않습니다 자식 노드로 이동하려는 두 번째 줄은 부모 요소를 변경합니다 ($ node는 참조이므로). 그렇게 할 수있는 비결이 있다면

내가 아무 생각이 없다, 나는 누군가가 나를

+0

우리에게'입력-Array'를 선언하는 코드를 보여주십시오. – Smandoli

+0

@Smandoli : 위 JSON 콘텐츠가있는 텍스트 파일이 있습니다. '$ input = json_decode (file_get_contents ("path.json"), true); ' – maja

+0

다른 형식을 갖도록 규칙을 변경할 수도 있지만 같은 기능이 필요합니다. – maja

답변

1

좋아, 여기에 몇 가지 결정 입니다하지만 당신은 $rules 구조를 변경해야, 그것은이 같은 $input과 같아야합니다 :

$input = json_decode('[{"meta":{"title": "Adressdata","name": "adress"},"data":{"desc":{"tooltip":"text","maxlength":"100"},"line1":{"tooltip":"Recipient","maxlength":"40"}}}]',true); 
$rules = json_decode('[{"meta":{"title": "Companyaddress"},"data":{"desc":{"tooltip":"Another Text","maxlength":"150"}}}]',true); 

// if you print both arrays you will see that they have the similar structure 
// but $rules consists only of items that you need to change. 
// next: 
echo'<pre>',print_r(array_replace_recursive($input, $rules)),'</pre>'; 

// BINGO! 
+0

간단하고 멋진 .. 나는 이것에 대해 결코 생각하지 못했을 것이다. 다르게 작동하는 단 한 가지가 있습니다. 노드를 객체로 대체하는 규칙이있을 때이 솔루션은 입력 배열에서 기존 내용을 삭제하지 않을 수 있습니다. 하지만 제 경우에는 문제가되지 않습니다. – maja

0

좋아, 약간의 실망 시간 후, 나는 마침내이를 달성하는 방법을 발견하는 데 도움 수 있기를 바랍니다.

이 내가 쓴 기능은 다음과 같습니다

/** 
* Manipulates an array according to the given rules 
*/ 
function manipulateData($input, $manipulations){ 

    foreach ($manipulations as $target => $replacement) { //for each rule 
     $tmpRefNum = 0;        //Variable-Nameprefix for the reference (don't generate random names) 

     $node = "node".(++$tmpRefNum);    //"node1" 
     $$node = &$input;       //$node1 --> $input 

     foreach (explode(">",$target) as $index) { //for each child in the rule   
      $parent = &$$node;      //We search for a child. So the old node becomes a parent 

      if(!isset($parent[$index])){    //Does the child exist?  no --> create missing child    
       $parent[$index] = "";    //give birth! (value will be set later)     
      } 

      $node = "node".(++$tmpRefNum);   //Generate a new reference-Name: "node2", "node3", ... 
      $$node = &$parent[$index];    //Point to child   
     } 

     $$node = $replacement;      //Change the child-content 

     //Unset all generated references (just to not spam the variables) 
     /* */ for($i=1;$i<=$tmpRefNum;$i++){ 
     /* */  $node = "node".$i; 
     /* */  unset($$node); 
     /* */ } 
     /* */ 
    } 
    return $input; 
} 

설명 :

솔루션 난 그냥 내가 찾아 각 자식 노드에 대한 새로운 변수/참조를 생성한다는 것이다. 이 작업을 수행하려면 PHP에서 제공하는 $$ - Syntax가 필요합니다.

가변 팩토리가 있기 때문에 약간 더러운 것입니다. 따라서 누군가가 더 나은 솔루션을 찾으면 멋질 것입니다.

좋은 해결책인지 아닌지 알려면 의견을 듣겠습니다.

관련 문제