note 111906 added to function.array-replace

From: Date: Wed, 10 Apr 2013 17:05:55 +0000
Subject: note 111906 added to function.array-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-194430@lists.php.net to get a copy of this message
In some cases you might have a structured array from the database and one of its nodes goes like this; <?php # a random node structure $arr = array( 'name' => 'some name', 'key2' => 'value2', 'title' => 'some title', 'key4' => 4, 'json' => '[1,0,1,1,0]' ); # capture these keys values into given order $keys = array( 'name', 'json', 'title' ); ?> Now consider that you want to capture $arr values from $keys. Assuming that you have a limitation to display the content into given keys order, i.e. use it with a vsprintf, you could use the following <?php # string to transform $string = "<p>name: %s, json: %s, title: %s</p>"; # flip keys once, we will use this twice $keys = array_flip( $keys ); # get values from $arr $test = array_intersect_key( $arr, $keys ); # still not good enough echo vsprintf( $string, $test ); // output --> name: some name, json: some title, title: [1,0,1,1,0] # usage of array_replace to get exact order and save the day $test = array_replace( $keys, $test ); # exact output echo vsprintf( $string, $test ); // output --> name: some name, json: [1,0,1,1,0], title: some title ?> I hope that this will save someone's time. ---- Server IP: 94.76.225.145 Probable Submitter: 87.202.17.55 ---- Manual Page -- http://php.net/manual/en/function.array-replace.php Edit -- https://master.php.net/note/edit/111906 Del: integrated -- https://master.php.net/note/delete/111906/integrated Del: useless -- https://master.php.net/note/delete/111906/useless Del: bad code -- https://master.php.net/note/delete/111906/bad+code Del: spam -- https://master.php.net/note/delete/111906/spam Del: non-english -- https://master.php.net/note/delete/111906/non-english Del: in docs -- https://master.php.net/note/delete/111906/in+docs Del: other reasons-- https://master.php.net/note/delete/111906 Reject -- https://master.php.net/note/reject/111906 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#194430) next »