Last active
September 4, 2020 13:59
-
-
Save janeklb/4761535 to your computer and use it in GitHub Desktop.
PHP: array to object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
# Simple loop copy | |
function loop_copy($array) { | |
$object = new stdClass(); | |
foreach ($array as $key => $value) { | |
$object->$key = $value; | |
} | |
} | |
# leveraging json_decode + json_encode | |
function json_copy($array) { | |
json_decode(json_encode($array), FALSE); | |
} | |
# http://pear.php.net/package/Benchmark/ | |
# http://pear.php.net/package/Benchmark/docs/1.2.9/Benchmark/Benchmark_Timer.html | |
require 'Benchmark/Timer.php'; | |
# prepare the arrays to be copied | |
$sizes = array(5, 20, 100, 500); | |
$arrays = array(); | |
foreach ($sizes as $size) { | |
$array = array(); | |
$i = $size; | |
while ($i-- >= 0) { | |
$key = uniqid('key'); | |
$array[$key] = uniqid('value'); | |
} | |
$arrays[] = $array; | |
} | |
# Prepare timer and iterations | |
$itera = array(100, 500, 1000); | |
foreach ($itera as $i) { | |
foreach ($arrays as $array) { | |
$array_len = count($array); | |
$timer = new Benchmark_Timer(TRUE); | |
$x = $i; | |
while ($x-- >= 0) { | |
json_copy($array); | |
} | |
$timer->setMarker("json_copy with $i copies of array size $array_len"); | |
$x = $i; | |
while ($x-- >= 0) { | |
loop_copy($array); | |
} | |
$timer->setMarker("loop_copy with $i copies of array size $array_len"); | |
$timer->display(); | |
} | |
} |
A small note must be done here: loop_copy($array)
is not recursive, while the json_copy($array)
is.
If we change line #7 from
$object->$key = $value
into
$object->$key = (is_array($value) ? loop_copy($value) : $value)
Then the loop_copy will be recursive. Correct me If I'm wrong.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@metalmatze these are the results from my Macbook 2,2 w/ PHP 5.3.15 (i7 @ 2.2Ghz)