Visualizzazione dei risultati da 1 a 2 su 2
  1. #1
    Utente di HTML.it
    Registrato dal
    Oct 2014
    Messaggi
    75

    Creare un array complesso

    Ciao a tutti, ho bisogno di un vostro aiuto. Devo creare un array "complesso" per poi poterlo convertirlo in json. Attualmente ho sempre fatto in questo modo:

    Codice PHP:
    //Prelevato i dati da un db mysql   
    $event_array[] = array(   'id' => $record['id'],   'nome' => $record['nome'],
       
    'cognome' => $record['cognome'],
       
    'citta' => $record['citta']
                );
     echo 
    json_encode($event_array); 
    Restituendo un file json cosi:


    [{
    "id": 1,
    "nome": 'Nicola',
    "cognome": 'Rossi',
    "citta": 'Roma'
    }]

    Io vorrei creare una cosa del genere:

    {
    "posts": [
    {
    "id": 1,
    "title": "Post 1"
    },
    {
    "id": 2,
    "title": "Post 2"
    },
    {
    "id": 3,
    "title": "Post 3"
    }
    ],
    "comments": [
    {
    "id": 1,
    "body": "some comment",
    "postId": 1
    },
    {
    "id": 2,
    "body": "some comment",
    "postId": 1
    }
    ],
    "profile": {
    "name": "typicode"
    }
    }

    Grazie

  2. #2
    Moderatore di PHP L'avatar di Alhazred
    Registrato dal
    Oct 2003
    Messaggi
    12,503
    Una cosa così
    Codice PHP:
    $event_array['posts'] = [
        [
    'id' => 1'title' => 'primo'],
        [
    'id' => 2'title' => 'secondo'],
        [
    'id' => 3'title' => 'terzo']
    ];
    $event_array['comments'] = [
        [
    'id' => 1'body' => 'uno''postId' => 1],
        [
    'id' => 2'body' => 'due''postId' => 2],
        [
    'id' => 3'body' => 'tre''postId' => 1]
    ];
    $event_array['profile'] = [ 'name' => 'typicode' ];

    echo 
    json_encode($event_array); 
    Ultima modifica di Alhazred; 07-04-2019 a 10:06

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.