I'm using Roots Sage 9, which uses Laravel within WordPress, and am combining this with Advanced Custom Fields.
For this, I have created a Controller, where I use an array_map to iterate through the returned array, to extract all of the date.
Depending on the page, I am sometimes returning an array with a 2nd level array within it, whilst on other occasions I am only returning an array with a single level.
The problem I run into, is in instances I only have a single level array, where the 2nd array_map returns with an error (array_map(): Argument #2 should be an array), as no array is present.
I assumed a ternary would solve this, but it doesn't seem to be the case
My question is, is it possible to create a function that uses array_map for these purposes?
My data, when it works, looks like this:
Array (
[0] => Array (
[identifier] => xyz
[description] => xyz
[bib_sources] => Array ( [0] =>
Array (
[type] => Book [year] => 1956
)
)
)
)
My data, when it doesn't work, looks like this:
Array (
[0] => Array (
[identifier] => xyz
[description] => xyz
[bib_sources] =>
)
)
My code looks like this:
public function states()
{
//type
$type = get_field('c_p_c_p_s_e_type', $post_id, false, false);
if($type == 'State & Edition') {
return array_map(function($states) {
return [
'identifier' => $states['s_identifier'] ?? null,
'description' => $states['s_description'] ?? null,
'impression_description' => $states['s_impression_description'] ?? null,
'component_of_image' => $states['s_textual_numerical_comp_of_image'] ?? null,
'inscriptions' => $states['s_inscriptions'] ?? null,
'artists_comments' => $states['s_artists_comments'] ?? null,
'authors_comments' => $states['s_authors_comments'] ?? null,
'image' => wp_get_attachment_image( $states['s_image'], 'medium' ) ?? null,
'related_works' => $states['s_related_works'] ?? null,
'final_state' => $states['s_final_state'] ?? null,
'ashkas' => $states['s_bib_source_c_bib_sources'] ?? null,
'bib_sources' => array_map(function($bib_sources) {
return [
'type' => $bib_sources['c_bib_sources_type'] ?? null,
'year' => $bib_sources['c_bib_sources_year'] ?? null,
'abb_ref' => get_term_by( 'id', $bib_sources['c_bib_sources_abbreviated_reference']->term_id, 'bib_sources') ?? null,
'citation' => $bib_sources['c_bib_sources_citation'] ?? null,
];
}, $states['s_bib_source_c_bib_sources'] ?? []),
];
}, get_field('c_states') ?? []);
}
}