0

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.

1
  • 1
    a combination of array_keys and get_object_vars should give a good place to start Commented Sep 24, 2023 at 18:16

3 Answers 3

2

If you assume that the above source data $custom_fields could be written like this in PHP:

$custom_fields=[
    (object)["foo"=>"bar"],
    (object)["something"=>"else"],
    (object)["two_words"=>"example"],
    (object)["qty"=>2],
    (object)["comments"=>"Hello World!"]
];

If this was json_encode(d) you would get:

[{"foo":"bar"},{"something":"else"},{"two_words":"example"},{"qty":2},{"comments":"Hello World!"}] // ie:as question source!

Then a combination of the foreach with array_keys and array_values applied to each child object, like this:

$notes='';
foreach( $custom_fields as $obj ){
    $key=array_keys( get_object_vars( $obj ) )[0];
    $val=array_values( get_object_vars( $obj ) )[0];
    $notes .= sprintf('%s: %s%s',$key,$val,PHP_EOL);
}
printf('<textarea cols=80 rows=5>%s</textarea>',$notes);

should yield:

<textarea cols=80 rows=5>
    foo: bar
    something: else
    two_words: example
    qty: 2
    comments: Hello World!
</textarea>

It should also be mentioned that one can use the second argument to json_decode which will force the returned output to be delivered as an associative array. With such output conventional foreach can be applied - where the nested objects will now be child arrays (so rather than an array of objects it is now an array of arrays )

$custom_fields = json_decode( $object->custom_fields, true );
$notes='';
foreach( $custom_fields as $index => $arr ){
    foreach( $arr as $key => $val )$notes .= sprintf('%s: %s%s',$key,$val,PHP_EOL);
}
printf('<textarea cols=80 rows=5>%s</textarea>',$notes);
Sign up to request clarification or add additional context in comments.

1 Comment

Your comment to explore array_keys and get_object_vars was super helpful - exactly the push I needed—thank you!!
0

Php class is iterable you can try this:

 <?php

$array = '{"custom_fields": [
    {"foo": "bar"},
    {"something": "else"},
    {"two_words": "example"},
    {"qty": 2},
    {"comments": "Hello World!"}
]}';

   $ar = json_decode($array);

   foreach($ar->custom_fields as $key => $obj ){
     foreach($obj as $property => $val){
        echo $property."=>".$val."\t\n";
     }
   }

Output:

foo=>bar
something=>else
two_words=>example
qty=>2
comments=>Hello World!

Comments

0

This should work:

function printLines(string $input, bool $print = true) {
    // If the first or last line is empty, trim it.
    $input = trim($input);
    $rows = explode(PHP_EOL, $input);
    foreach($rows as $index => $row) {
        $row = trim($row);
        if(empty($row)) {
            //If the line is empty, nothing to print.
            unset($rows[$index]);
            continue;
        }
        $row = explode(':', $row);
        $row[1] = $row[1] ?? '';
        $rows[$index] = $row;
        if($print) {
            echo "{$row[0]}: {$row[1]}" . PHP_EOL;
        }
    }
    
    return array_values($rows);
}

DEMO: https://onlinephp.io/c

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.