I have one dynamic multidimensional-array having unknown depth. I wanted to replace a key=>value based on another key=>value condition.
E.g replace $settings[$cient_id]'s value when $form_id is 1f44537.
$data = array (
0 =>
array (
'id' => '2cd5985',
'elType' => 'section',
'settings' => array(),
'elements' => array (
0 => array (
'id' => '88063e6',
'elType' => 'column',
'settings' => array(),
'elements' => array (
0 =>
array (
'id' => '1f44537',
'elType' => 'widget',
'settings' => array (
'ap_google_sheet_client_id' => 'test_id',
),
'elements' => array (
),
'widgetType' => 'form',
),
)
),
1 => array (
'id' => '7878c73',
'elType' => 'column',
'settings' => array(),
'elements' => array (
0 =>
array (
'id' => '1f44537',
'elType' => 'widget',
'settings' => array (
'ap_google_sheet_client_id' => 'test_id',
),
'elements' => array (
),
'widgetType' => 'form',
),
)
),
),
),
);
Here are my unsuccessful tries
Try-1
public function replace_recursive( $elements, $form_id ) {
foreach ( $elements as &$element) {
if ( $element['id'] === $form_id ) {
$element['settings']['ap_google_sheet_client_id'] = 'replaced';
return $elements;
}
if ( ! empty( $element['elements'] ) ) {
$elements = self::replace_recursive( $element['elements'], $form_id );
if ( $elements ) {
return $elements;
}
}
}
}
Try-2
This solved the issue. But the loop doesn't stop when found the element. It loops through all the elements.
public function replace_recursive( $elements, $form_id ) {
foreach ( $elements as &$element) {
if ( $element['id'] === $form_id ){
$element['settings']['ap_google_sheet_client_id'] = 'replaced';
write_log('A');
break;
}
if ( ! empty( $element['elements'] ) ) {
self::replace_recursive( $element['elements'], $form_id );
write_log('B');
}
}
return $elements;
}
Value replaced but I am not getting the full array $elements. Rather than getting the child array for which the value was replaced.
Try-3
Facing the same issue again. The named keys that are on top of elType=widget are converted to numbered keys. Here is a sandbox.
https://sandbox.onlinephpfunctions.com/code/530fb53612dd7a2017b236f218665c0142f1e63f
var_exportof your array rather than print_r().replace_recursivetakes two arguments, show representative code that lets folks run that function, on that representative data.