2014-05-16 3 views
0

에 대한 쿼리를 선택했습니다. 실제로 붙어있어이 문제를 해결할 방법을 모르겠습니다. 선택한 테이블의 다차원 연관 배열이되도록 MySQL 데이터베이스를 쿼리하고 싶습니다. 이것은 내가 지금까지 무엇을 가지고 있지만으로 이어질하지 않습니다json에 대한 다차원 배열

{ 
    "table1name": [ 
     { 
      "field1": "a", 
      "field2": "b", 
     }, 
    { 
      "field1": "c", 
      "field2": "d" 
    } 
    ], 
    "table2name": [ 
     { 
      "fieldx": "1", 
      "fieldy": "2", 
     }, 
     { 
      "fieldx": "3", 
      "fieldy": "4" 
     } 
    ], 
    "table3name": [ 
     { 
      "fieldz": "1", 
      "fieldq": "2", 
     }, 
     { 
      "fieldz": "3", 
      "fieldq": "4" 
     } 
    ] 
} 

: 나는, 결과는 다음과 같아야합니다 json_encode($ar)으로 인코딩한다면

$ar = Array(
    table1name=>Array(Array(field1=>a, field2=>b), Array(field1=>a, field2=>b)), 
    table2name=>Array(Array(field1=>a, field2=>b), Array(field1=>a, field2=>b)), 
    table3name=>Array(Array(field1=>a, field2=>b), Array(field1=>a, field2=>b)), 

); 

:
이 배열은 내 목표 예상 결과 :

function tablesToJson() 
{ 
    $mysqli = new mysqli("localhost", "user", "password", "test"); 
    $tables = Array(); 
    array_push($tables, "table1name"); 
    array_push($tables, "table2name"); 
    $finalArray = Array(); 

    foreach ($tables as $table) { 
     if ($result = $mysqli->query('SELECT * FROM ' . $table)) { 

      $rows = Array(); 
      while ($row = $result->fetch_assoc()) { 
       $rows[] = $row; 
      } 
      array_push($finalArray, $rows); 
     } 
    } 
    return $finalArray; 
} 
+0

그럼, 결과는 무엇입니까? 어떤 mysql 오류가 발생합니까 아니면 객체/배열이 잘못된 것입니까? –

+0

예, 다음과 같이 형식이 잘못되었습니다 :'[[ "id": "1", "field2": null, "field3": null}, {next object}]] ' – toefftoefftoeff

+1

ah thanks ... 바로 실수. 나는 너에게 답을 줄 것 같아. 문제는 바로 테이블에 누락 된 열쇠입니까? –

답변

1

마지막 배열에 테이블 결과를 추가 할 때 키를 사용하는 것을 잊었거나 놓치 셨습니다. 그래서 당신은 당신의 요청 키로 $table를 가진 당신의 finalResult에 새 key>element 조합을 설정

$finalArray[$table] = $rows; 

: 그래서 대신

array_push($finalArray, $rows); 

당신은 같은 것을 사용한다.

function tablesToJson() 
{ 
    $mysqli = new mysqli("localhost", "user", "password", "test"); 
    $tables = Array(); 
    array_push($tables, "table1name"); 
    array_push($tables, "table2name"); 
    $finalArray = Array(); 

    foreach ($tables as $table) { 
     if ($result = $mysqli->query('SELECT * FROM ' . $table)) { 

      $rows = Array(); 
      while ($row = $result->fetch_assoc()) { 
       $rows[] = $row; 
      } 
      $finalArray[$table] = $rows; 
     } 
    } 
    return $finalArray; 
}