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 Perchpole - April 2, 2015

Greg -

Just one final thing...

As a rule, if we need to return an array from which we only require one or two elements, is it always better to set up a simple query as opposed to loading everything with a getRecords call?

Thanks,

Perch