Creating a Filtered Array from Another Array

5 posts by 2 authors in: Forums > CMS Builder
Last Post: April 2, 2015   (RSS)

By Perchpole - April 2, 2015

Hello, All

I want to create a "slimmed down" version of an array from an existing array. During the process I want to drop several columns which are no longer needed. I believe I can do this using the unset command like this...

<?php
list($allPages) = getRecords(array(
'tableName' => 'pages',
'allowSearch' => false,
));
?>

<?php $allPagesNew = array(); ?>

<?php foreach($allPages as $row): ?>
  <?php unset($row['dontWantThis']); ?>
  <?php $allPagesNew[] = $row; ?>
<?php endforeach ?>

...but what happens if I want to lose lots of columns? Or, to put it another way, how do I choose what I want to keep and ignore the rest?

:o/

Perch

By gregThomas - April 2, 2015

Hey Perch,

The getRecords function is designed to return all columns to reduce its complexity and make it easy to work with. It doesn't contain a way to select which columns are returned.

If you wanted to only return specific columns, I'd recommend writing a custom select query, and using the mysql_select_query function to run the command, for example:

showme(mysql_select_query("SELECT `title`, `content` FROM `pages` WHERE `hidden` = '0' ORDER BY `createdDate`"));

The function above would only return the title and content fields. 

If you use the method in your previous post, there shouldn't be any negative impacts unless you try to access a variable you've unset. 

Cheers!

Greg

Greg Thomas







PHP Programmer - interactivetools.com

By Perchpole - April 2, 2015

OK. Cheers, Greg.

:0)

By gregThomas - April 2, 2015

Hey Perch,

99.5% of the time I use either getRecords or mysql_select, even though these two functions return all of the fields for the records they return.

Computing power on hosting services is now enough that you don't really need to worry about optimising on that level until sites become Really heavily used, or you're returning large MySQL calls (over 50 rows). Also, in most situations its actually cheaper to upgrade your hosting servers than it is to spend the time optimizing all of your MySQL calls on that level.

Having said that, ensuring that you're returning as few rows as possible, and optimising any large MySQL calls to run as infrequently as possible (for example, by saving meta data for a record against it using a cron job) are still optimizations that are worth carrying out. 

Cheers!

Greg

Greg Thomas







PHP Programmer - interactivetools.com