0

So have a simple Field a user can enter some IDs in:

<field name="ids" type="subform" min="1" multiple="true" layout="joomla.form.field.subform.repeatable-table" buttons="add,remove" groupByFieldset="false" label="IDs">
    <form>
        <fieldset name="section1" label="Section1">
            <field name="id" label="ID" min="0" type="number" />
        </fieldset>
    </form>
</field>

If i want fo get the IDs as a simple array. At the moment i do this:

$ids = array_column(json_decode(json_encode($this->params->get('ids')), TRUE), 'id');

That looks a bit weird, but i want to avoid using loops. Is there a framework friendly approach to this?

1 Answer 1

1

Since PHP 7 array_column() supports passing an array of objects. You would only need to cast the data to array:

$ids = array_column((array) $this->params->get('ids'), 'id');

On older PHP versions you could cast to array and use Joomla\Utilities\ArrayHelper::getColumn() which supports passing array of objects on all PHP versions:

use Joomla\Utilities\ArrayHelper;

$ids = ArrayHelper::getColumn((array) $this->params->get('ids'), 'id');

Or, alternatively, use Joomla\Utilities\ArrayHelper::fromObject() to recursively convert the object to an array and then use array_column():

use Joomla\Utilities\ArrayHelper;

$ids = array_column(ArrayHelper::fromObject($this->params->get('ids')), 'id');

I have not measured how performance compares to JSON encode/decode.

2
  • Sharky, does $this->params->get('ids') return an object of objects? Feb 18, 2021 at 21:52
  • 1
    Yes, repeatable subform normally stores data as an object of objects.
    – Sharky
    Feb 18, 2021 at 22:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.