简体   繁体   中英

Multidimensional PHP array in for loop as JSON

I have problem with showing my php array as a json object. I want to fill the array with data from databases in a php for loop so I can make an json object out of it so I can use it in javascript.

When I log the data in the console using GetJSON it won't show the data like 'id' but it does show up when I echo the JSON in php. The value in 'name' is filled outside the for loop, to test if my array works as json object.

在此处输入图片说明

<script type='text/javascript'>
    $(document).ready(function(){

      $.getJSON('database/getTourInfo.php', function(data) {
        console.log(data);
          $.each(data, function(key, val) {
            console.log(val.show.name);
          });
      });

    });
  </script>

This is the getTourInfo.php. When I fill the value's of the array OUTSIDE the for loop it will output in the console ( see 'name' ). But when I fill it in the for loop as seen below, it will appear in the JSON when I echo it but wont show in the console.

<?php

header("Content-type: text/javascript");

$x = 0;
$tourInfo  = array();
$tourInfo_array = array (
  "show"      => array(
          "id" => "", 
          "name" => "Naam1", 
          "date" => "", 
          "support" => "", 
          "festival" => ""
  ),
  "location"  => array(
          "latitude" => "",
          "longitude" => ""
  ),
  "venue"     => array(
          "name" => "", 
          "space" => "", 
          "capacity" => ""
  ),
  "people"    => array(
          "attending" => "",
           "interested" => ""
  )        
);

$tourdates = json_decode( $tourdatesJSON, true );
foreach($tourdates as $tourdate) { 
  $x++;

  $event_page_id  = $tourdate['ShowEventpage'];
  $festival       = $tourdate['ShowFestival'];
  $support        = $tourdate['ShowVoorprogramma'];

  $tourdates_array[$x]["show"]["id"] = $event_page_id;
  $tourdates_array[$x]["show"]["support"] = $support;
  $tourdates_array[$x]["show"]["festival"] = $festival;

  array_push($tourInfo, $tourInfo_array[$x]);

}

$tourInfoJSON = json_encode($tourInfo, JSON_PRETTY_PRINT);
echo $tourInfoJSON;
?>

How can I fill my multidimensional array in a for loop and output it as json with getJSON?

Have you tried this?

header('Content-Type: application/json');

echo json_encode($tourInfo, JSON_PRETTY_PRINT);

Judging by the expected output of the query, I think you have gone about the construction a little wrong.

Try this;

<?php

$tourdate = array(
  '2016-03-01' => array(
    'ShowEventpage' => '1',
    'ShowFestival' => 'Isle of Wight',
    'ShowVoorprogramma' =>'N'
    ),
  '2016-04-01' => array(
    'ShowEventpage' => '2',
    'ShowFestival' => 'V Festival',
    'ShowVoorprogramma' =>'N'
    ),
  '2016-05-01' => array(
    'ShowEventpage' => '3',
    'ShowFestival' => 'Glastonbury',
    'ShowVoorprogramma' =>'Y'
    ),
  '2016-06-01' => array(
    'ShowEventpage' => '4',
    'ShowFestival' => '1Xtra',
    'ShowVoorprogramma' =>'Y'
    ),
  '2016-07-01' => array(
    'ShowEventpage' => '5',
    'ShowFestival' => 'Party in the Park',
    'ShowVoorprogramma' =>'N'
    )
  );

$tourdatesJSON = json_encode($tourdate);


$x = 0;
$tourInfo  = array();
$tourInfo_array = array (
  "location"  => array(
          "latitude" => "",
          "longitude" => ""
  ),
  "venue"     => array(
          "name" => "", 
          "space" => "", 
          "capacity" => ""
  ),
  "people"    => array(
          "attending" => "",
           "interested" => ""
  )        
);

$tourdates = json_decode( $tourdatesJSON, true );
$tourdates_array = array();

$i = intval(0);
foreach($tourdates as $date)
{ //Foreach through list of dates

    $tourdates_array[] = array(
      'show' => array(
        'id' => $date['ShowEventpage'],
        'support' => $date['ShowVoorprogramma'],
        'festival' => $date['ShowFestival']
        ),
        "location"  => array(
                "latitude" => "",
                "longitude" => ""
        ),
        "venue"     => array(
                "name" => "", 
                "space" => "", 
                "capacity" => ""
        ),
        "people"    => array(
                "attending" => "",
                 "interested" => ""
        )  
    );    
    $i++;
}

$tourInfoJSON = json_encode($tourdates_array, JSON_PRETTY_PRINT);


header("Content-type: application/json");
echo $tourInfoJSON;
?>

This is what I get when I run this on command line;

[
    {
        "show": {
            "id": "1",
            "support": "N",
            "festival": "Isle of Wight"
        },
        "location": {
            "latitude": "",
            "longitude": ""
        },
        "venue": {
            "name": "",
            "space": "",
            "capacity": ""
        },
        "people": {
            "attending": "",
            "interested": ""
        }
    },
    {
        "show": {
            "id": "2",
            "support": "N",
            "festival": "V Festival"
        },
        "location": {
            "latitude": "",
            "longitude": ""
        },
        "venue": {
            "name": "",
            "space": "",
            "capacity": ""
        },
        "people": {
            "attending": "",
            "interested": ""
        }
    },
    {
        "show": {
            "id": "3",
            "support": "Y",
            "festival": "Glastonbury"
        },
        "location": {
            "latitude": "",
            "longitude": ""
        },
        "venue": {
            "name": "",
            "space": "",
            "capacity": ""
        },
        "people": {
            "attending": "",
            "interested": ""
        }
    },
    {
        "show": {
            "id": "4",
            "support": "Y",
            "festival": "1Xtra"
        },
        "location": {
            "latitude": "",
            "longitude": ""
        },
        "venue": {
            "name": "",
            "space": "",
            "capacity": ""
        },
        "people": {
            "attending": "",
            "interested": ""
        }
    },
    {
        "show": {
            "id": "5",
            "support": "N",
            "festival": "Party in the Park"
        },
        "location": {
            "latitude": "",
            "longitude": ""
        },
        "venue": {
            "name": "",
            "space": "",
            "capacity": ""
        },
        "people": {
            "attending": "",
            "interested": ""
        }
    }
]

The main issue with what you were doing, was that you are defining the $tourInfo_array array, and then trying to add information into it. So when you try to output the array from there, everything you have put into the array initially, still remains as it is, and the loop simply adds new entries to the bottom.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM