skip to Main Content

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


  1. 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>
    
    Login or Signup to reply.
  2. 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."tn";
         }
       }
    

    Output:

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

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search