简体   繁体   中英

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;

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
              );

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