php 如何动态输出对象数组的key:value?

im9ewurl  于 9个月前  发布在  PHP
关注(0)|答案(3)|浏览(73)

我有一个对象数组,看起来像这样:

$custom_fields = json_decode($object->custom_fields);

// output: 
"custom_fields": [
    {"foo": "bar"},
    {"something": "else"},
    {"two_words": "example"},
    {"qty": 2},
    {"comments": "Hello World!"}
]

我使用this S.O. thread来查看如何输出值。但是,在该线程中,密钥始终相同。
我试图完成的是用这些键/值填充textarea

Foo: bar
Something: else
Two words: example
Qty: 2
Comments: Hello World!

我可以硬编码这些值;理想情况下,我希望它是动态的。这意味着,custom_fields数组中的任何内容都会被输出。我可能会在将来添加或删除属性,所以没有硬编码是理想的。
以下是我目前拥有的:

$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;

结果如下:

Foo: bar
Something: else
Two Words: example
Qty: 2
Comments: Hello World!

如何循环数组并动态输出键Foo和值bar
接下来我将使用str_replace或其他东西将two_words解析为Two words

b5lpy0ml

b5lpy0ml1#

假设上面的源数据$custom_fields可以用PHP写成这样:

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

如果这是json_encode(d),你会得到:

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

然后将foreacharray_keysarray_values的组合应用于每个子对象,如下所示:

$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);

应产生:

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

还应该提到的是,可以使用json_decode的第二个参数,这将强制返回的输出作为关联数组传递。有了这样的输出,可以应用传统的foreach-其中嵌套的对象现在将是子数组(因此,而不是对象的数组,它现在是数组的数组)

$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);
rm5edbpk

rm5edbpk2#

Php类是可迭代的,你可以试试这个:

<?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";
     }
   }

输出量:
foo=>bar
其他=>其他
两个词=>示例
数量=>2
你好,世界!

0wi1tuuw

0wi1tuuw3#

这应该是可行的:

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);
}

DEMOhttps://onlinephp.io/c

相关问题