I have an array of objects that looks like this:
$custom_fields = json_decode($object->custom_fields);
// output:
"custom_fields": [
{"foo": "bar"},
{"something": "else"},
{"two_words": "example"},
{"qty": 2},
{"comments": "Hello World!"}
]
I have used this S.O. thread to see how I can output the values. However, in that thread the key is always the same.
What I am trying to accomplish is to populate a textarea
with these key/values.
Foo: bar
Something: else
Two words: example
Qty: 2
Comments: Hello World!
I could hard-code these values; ideally I’d like it to be dynamic. Meaning, whatever is in the custom_fields
array gets outputted. I may add or remove attributes in the future so not having things hard-coded is ideal.
Here’s what I currently have:
$notes_arr = [];
foreach ($custom_fields as $field) {
$notes_arr[] = $field;
}
$notes = 'Foo: ' . $notes_arr[0]->foo . PHP_EOL;
$notes .= 'Something: ' . $notes_arr[0]->something . PHP_EOL;
$notes .= 'Two Words: ' . $notes_arr[0]->two_words . PHP_EOL;
$notes .= 'Qty: ' . $notes_arr[0]->qty . PHP_EOL;
$notes .= 'Comments: ' . $notes_arr[0]->comments . PHP_EOL;
Which results in this:
Foo: bar
Something: else
Two Words: example
Qty: 2
Comments: Hello World!
How can I loop through the array & output the key Foo
and the value bar
dynamiclly?
I will work to resolve the two_words
into Two words
using str_replace
or something next.
3
Answers
If you assume that the above source data
$custom_fields
could be written like this in PHP:If this was
json_encode(d)
you would get:Then a combination of the
foreach
witharray_keys
andarray_values
applied to each child object, like this:should yield:
Php class is iterable you can try this:
This should work:
DEMO: https://onlinephp.io/c