Skip to content

Instantly share code, notes, and snippets.

@janeklb
Last active September 4, 2020 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janeklb/4761535 to your computer and use it in GitHub Desktop.
Save janeklb/4761535 to your computer and use it in GitHub Desktop.
PHP: array to object
<?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();
}
}
@nidhviadmin
Copy link

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.

@janeklb
Copy link
Author

janeklb commented Sep 4, 2020

You'd have to make a few other changes to make it truly recursive (ie, handle is_object($value) too) but yeah -- could totally make it recursive

That said bear in mind :)
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment