在某些情況下,您可能會從資料庫中得到一個結構化陣列,其中
一個節點如下所示:
<?php
$arr = array(
'name' => 'some name',
'key2' => 'value2',
'title' => 'some title',
'key4' => 4,
'json' => '[1,0,1,1,0]'
);
$keys = array( 'name', 'json', 'title' );
?>
現在假設您想要從 $keys 中擷取 $arr 的值。
假設您在顯示內容時受到指定鍵順序的限制,
例如,將其與 vsprintf 一起使用,您可以使用以下方法
<?php
$string = "<p>name: %s, json: %s, title: %s</p>";
$keys = array_flip( $keys );
$test = array_intersect_key( $arr, $keys );
echo vsprintf( $string, $test );
$test = array_replace( $keys, $test );
echo vsprintf( $string, $test );
?>
我希望這可以節省某人的時間。