Search code examples
phpwordpress-rest-api

Loop over query and add each item as associative array in one multi-dimensional array


I would like to loop over records, retrieve multiple properties and values for each item and then keep pushing each item as an associative array using name/value pairs into one large multidimensional array .

For example, in my loop I have 2 records, but my associate arrays keep getting written over. How can I just push associate arrays.

My code is only returning one key, although it should return two.

PHP

    // loop over wordpress posts
    while ( have_posts() ) : the_post();
        $propertytype = get_field('PropertyType');
        $propertyname = get_field('PropertyName');
        $propertylocation = get_field('PropertyLocation');
        $propertydescr = get_field('PropertyDescription');
        $propertydphone = get_field('PropertyPhone');
        $propertywebsite = get_field('PropertyWebsite');
        $propertystatus = get_field('PropertyStatus');
        $propertythumb = get_field('PropertyThumbnail');
        $propertylargeimage = get_field('PropertyLargeImage');

        //add each record as an associative array
        $data1 = array(
            'PropertyType' => $propertytype,
            'PropertyName' => $propertyname,
            'PropertyLocation' => $propertylocation,
            'PropertyDescription' => $propertydescr,
            'PropertyPhone' => $propertydphone,
            'PropertyWebsite' => $propertywebsite,
            'PropertyStatus' => $propertystatus,
            'PropertyThumbnail' => $propertythumb,
            'PropertyLargeImage' => $propertylargeimage
          );
    endwhile;

Solution

  • Define $data1 as array before you start the loop

    $data1[] = []; // or array() for backwards compatibility
    

    inside the loop

    $data1[] = array(
                    'PropertyType' => $propertytype,
                    'PropertyName' => $propertyname,
                    'PropertyLocation' => $propertylocation,
                    'PropertyDescription' => $propertydescr,
                    'PropertyPhone' => $propertydphone,
                    'PropertyWebsite' => $propertywebsite,
                    'PropertyStatus' => $propertystatus,
                    'PropertyThumbnail' => $propertythumb,
                    'PropertyLargeImage' => $propertylargeimage
                  );