flat array to tree array - php

I am currently stuck on the modification of an array "flat" to a array structure of a tree.
I have an array to the type:
$folders = array(
array('Name' => 'Archive', 'Value' => 'Archive', 'Attributes' => 32, 'Delimiters' => '/'),
array('Name' => 'Folder1', 'Value' => 'Archive/Folder1', 'Attributes' => 32, 'Delimiters' => '/'),
array('Name' => 'FolderA', 'Value' => 'Archive/Folder1/DossierA', 'Attributes' => 64, 'Delimiters' => '/'),
array('Name' => 'Folder2', 'Value' => 'Archive/Folder2', 'Attributes' => 32, 'Delimiters' => '/'),
array('Name' => 'FolderA', 'Value' => 'Archive/Folder2/FolderA', 'Attributes' => 32, 'Delimiters' => '/'),
array('Name' => 'FolderB', 'Value' => 'Archive/Folder2/FolderA/FolderB', 'Attributes' => 64, 'Delimiters' => '/'),
);
and I would get an array to the type:
$treefolders = array(
array('Name' => 'Archive', 'Value' => 'Archive', 'Attributes' => 32, 'Delimiters' => '/', 'subnode' =>
array('Name' => 'Folder1', 'Value' => 'Archive/Folder1', 'Attributes' => 32, 'Delimiters' => '/', 'subnode' =>
array('Name' => 'FolderA', 'Value' => 'Archive/Folder1/FolderA', 'Attributes' => 64, 'Delimiters' => '/')
),
array('Name' => 'Folder2', 'Value' => 'Archive/Folder2', 'Attributes' => 32, 'Delimiters' => '/', 'subnode' =>
array('Name' => 'FolderA', 'Value' => 'Archive/Folder2/FolderA', 'Attributes' => 32, 'Delimiters' => '/', 'subnode' =>
array('Name' => 'FolderB', 'Value' => 'Archive/Folder2/FolderA/FolderB', 'Attributes' => 64, 'Delimiters' => '/')
)
)
)
);
I do not know how to get to the last result.
Can you help me?

This is not possible, in PHP arrays cannot be used as array keys. You are able to use just the directory name as a key.
The best solution is to change the way you create your array or rethink your code and/or data structure. There is probably a much easier solution to your problem, maybe re-ask your question. See the XY problem.

Sorry I have done anything in my first post
Here is the structure of my array "flat":
Array
(
[0] =>
Array
(
'Name' => 'Archive'
'Value' => 'Archive'
'Attributes' => 32
'Delimiters' => '/'
)
[1] =>
Array
(
'Name' => 'Folder1'
'Value' => 'Archive/Folder1'
'Attributes' => 32
'Delimiters' => '/'
)
[2] =>
Array
(
'Name' => 'FolderA'
'Value' => 'Archive/Folder1/DossierA'
'Attributes' => 64
'Delimiters' => '/'
)
[3] =>
Array
(
'Name' => 'Folder2'
'Value' => 'Archive/Folder2'
'Attributes' => 32
'Delimiters' => '/'
)
[4] =>
Array
(
'Name' => 'FolderA'
'Value' => 'Archive/Folder2/FolderA'
'Attributes' => 32
'Delimiters' => '/'
)
[5] =>
Array
(
'Name' => 'FolderB'
'Value' => 'Archive/Folder2FolderA/FolderB'
'Attributes' => 64
'Delimiters' => '/'
)
)
And that I am seeking:
Array
(
[0] =>
Array
(
'Name' => 'Archive'
'Value' => 'Archive'
'Attributes' => 32
'Delimiters' => '/'
'SubNode' =>
Array
(
[0] =>
Array
(
'Name' => 'Folder1'
'Value' => 'Archive/Folder1'
'Attributes' => 32
'Delimiters' => '/'
'SubNode' =>
Array
(
[0] =>
Array
(
'Name' => 'FolderA'
'Value' => 'Archive/Folder1/DossierA'
'Attributes' => 64
'Delimiters' => '/'
)
)
)
[1] =>
Array
(
'Name' => 'Folder2'
'Value' => 'Archive/Folder2'
'Attributes' => 32
'Delimiters' => '/'
'SubNode' =>
Array
(
[0] =>
Array
(
'Name' => 'FolderA'
'Value' => 'Archive/Folder2/FolderA'
'Attributes' => 32
'Delimiters' => '/'
'SubNode' =>
Array
(
[0] =>
Array
(
'Name' => 'FolderB'
'Value' => 'Archive/Folder2/FolderA/FolderB'
'Attributes' => 64
'Delimiters' => '/'
)
)
)
)
)
)
)
)
The normally its should be possible ^^

Related

Extract value from array php [duplicate]

This question already has answers here:
Find value of sibling key in php array
(4 answers)
Closed 3 years ago.
I have the following array of data and I am trying to access the tracking number field.
Someting like:
$array->meta_data->TrackingNumber
After 3 hours I cannot find a way to access it.
Any help much appreciated.
array (
'id' => 448,
'parent_id' => 0,
'status' => 'completed',
'currency' => 'GBP',
'version' => '3.7.1',
'prices_include_tax' => true,
'meta_data' =>
array (
0 =>
array (
'id' => 8041,
'key' => 'is_vat_exempt',
'value' => 'no',
),
1 =>
array (
'id' => 8043,
'key' => '_wpam_id',
'value' => '4',
),
2 =>
array (
'id' => 8046,
'key' => '_woo_pp_txnData',
'value' =>
array (
'refundable_txns' =>
array (
0 =>
array (
'txnID' => '1U998392V9620752U',
'amount' => '5.95',
'refunded_amount' => 0,
'status' => 'Completed',
),
),
'txn_type' => 'sale',
),
),
3 =>
array (
'id' => 8056,
'key' => 'Payer PayPal address',
'value' => 'anthony#befive.co.uk',
),
4 =>
array (
'id' => 8057,
'key' => 'Payer first name',
'value' => 'Anthony',
),
5 =>
array (
'id' => 8058,
'key' => 'Payer last name',
'value' => 'Evans',
),
6 =>
array (
'id' => 8059,
'key' => 'Payment type',
'value' => 'instant',
),
7 =>
array (
'id' => 8060,
'key' => '_paypal_status',
'value' => 'completed',
),
8 =>
array (
'id' => 8061,
'key' => '_paypal_transaction_fee',
'value' => '0.47',
),
9 =>
array (
'id' => 8290,
'key' => 'TrackingNumber',
'value' => '10046182',
),
10 =>
array (
'id' => 8291,
'key' => 'CarrierName',
'value' => 'SEABOURNE',
),
11 =>
array (
'id' => 10349,
'key' => '_alg_wc_custom_order_number',
'value' => '6',
),
),
'line_items' =>
array (
48 =>
array (
),
),
'tax_lines' =>
array (
50 =>
array (
),
),
'shipping_lines' =>
array (
49 =>
array (
),
),
'fee_lines' =>
array (
),
'coupon_lines' =>
array (
51 =>
array (
),
),
)
You're trying to access your array with $array->value, but the correct syntax would be $array['value']
I would loop through the meta data and check each key to see if is equals "tracking number" then echo out or do whatever you want with the result!
<?php
$test =array (
'id' => 448,
'parent_id' => 0,
'status' => 'completed',
'currency' => 'GBP',
'version' => '3.7.1',
'prices_include_tax' => true,
'meta_data' =>
array (
0 =>
array (
'id' => 8041,
'key' => 'is_vat_exempt',
'value' => 'no',
),
1 =>
array (
'id' => 8043,
'key' => '_wpam_id',
'value' => '4',
),
2 =>
array (
'id' => 8046,
'key' => '_woo_pp_txnData',
'value' =>
array (
'refundable_txns' =>
array (
0 =>
array (
'txnID' => '1U998392V9620752U',
'amount' => '5.95',
'refunded_amount' => 0,
'status' => 'Completed',
),
),
'txn_type' => 'sale',
),
),
3 =>
array (
'id' => 8056,
'key' => 'Payer PayPal address',
'value' => 'anthony#befive.co.uk',
),
4 =>
array (
'id' => 8057,
'key' => 'Payer first name',
'value' => 'Anthony',
),
5 =>
array (
'id' => 8058,
'key' => 'Payer last name',
'value' => 'Evans',
),
6 =>
array (
'id' => 8059,
'key' => 'Payment type',
'value' => 'instant',
),
7 =>
array (
'id' => 8060,
'key' => '_paypal_status',
'value' => 'completed',
),
8 =>
array (
'id' => 8061,
'key' => '_paypal_transaction_fee',
'value' => '0.47',
),
9 =>
array (
'id' => 8290,
'key' => 'TrackingNumber',
'value' => '10046182',
),
10 =>
array (
'id' => 8291,
'key' => 'CarrierName',
'value' => 'SEABOURNE',
),
11 =>
array (
'id' => 10349,
'key' => '_alg_wc_custom_order_number',
'value' => '6',
),
),
'line_items' =>
array (
48 =>
array (
),
),
'tax_lines' =>
array (
50 =>
array (
),
),
'shipping_lines' =>
array (
49 =>
array (
),
),
'fee_lines' =>
array (
),
'coupon_lines' =>
array (
51 =>
array (
),
),
);
foreach($test['meta_data'] as $data){
if($data['key'] === "TrackingNumber"){
echo "The tracking number is: " . $data['value'];
}
}

php Class Redis not found on mac

Php version:
enter image description here
When I request one of the interface of my CodeIgniter project and echo phpinfo(), there is no redis extension in the message.And the project loaded the wrong version of php like:
enter image description here
Yes I have multiple version of php in my MacOS.
Can anyone help me with this?
My project has this error msg:
ERROR - 2019-01-09 04:18:05 --> Exception:Error::__set_state(array(
'message' => 'Class \'Redis\' not found',
'string' => '',
'code' => 0,
'file' => '/Users/charlie/IdeaProjects/my_project/src/application/libraries/My_Redis.php',
'line' => 93,
'trace' =>
array (
0 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/application/libraries/My_Redis.php',
'line' => 51,
'function' => '_init',
'class' => 'My_Redis',
'type' => '->',
'args' =>
array (
0 =>
array (
'host' => '',
'port' => 6379,
'password' => '',
'timeout' => 2,
'persistent' => 0,
),
),
),
1 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/application/libraries/My_Redis.php',
'line' => 35,
'function' => 'getInstance',
'class' => 'My_Redis',
'type' => '->',
'args' =>
array (
0 => 'supply_chain_busi',
),
),
2 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/system/core/Loader.php',
'line' => 1095,
'function' => '__construct',
'class' => 'My_Redis',
'type' => '->',
'args' =>
array (
0 => 'supply_chain_busi',
),
),
3 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/system/core/Loader.php',
'line' => 975,
'function' => '_ci_init_class',
'class' => 'CI_Loader',
'type' => '->',
'args' =>
array (
0 => 'my_redis',
1 => '',
2 =>
array (
0 => 'supply_chain_busi',
),
3 => 'redis',
),
),
4 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/system/core/Loader.php',
'line' => 216,
'function' => '_ci_load_class',
'class' => 'CI_Loader',
'type' => '->',
'args' =>
array (
0 => 'My_Redis',
1 =>
array (
0 => 'supply_chain_busi',
),
2 => 'redis',
),
),
5 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/application/libraries/Tank_auth.php',
'line' => 45,
'function' => 'library',
'class' => 'CI_Loader',
'type' => '->',
'args' =>
array (
0 => 'My_Redis',
1 =>
array (
0 => 'supply_chain_busi',
),
2 => 'redis',
),
),
6 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/system/core/Loader.php',
'line' => 1095,
'function' => '__construct',
'class' => 'Tank_auth',
'type' => '->',
'args' =>
array (
0 =>
array (
'website_name' => 'mycom',
'webmaster_email' => 'webmaster#mycom.com',
'phpass_hash_portable' => true,
'phpass_hash_strength' => 8,
'allow_registration' => false,
'captcha_registration' => false,
'email_activation' => false,
'email_activation_expire' => 172800,
'email_account_details' => true,
'use_username' => true,
'username_min_length' => 4,
'username_max_length' => 20,
'password_min_length' => 4,
'password_max_length' => 20,
'login_by_username' => true,
'login_by_email' => true,
'login_record_ip' => true,
'login_record_time' => true,
'login_count_attempts' => true,
'login_max_attempts' => 99,
'login_attempt_expire' => 86400,
'autologin_cookie_name' => 'autologin',
'autologin_cookie_life' => 2592000,
'forgot_password_expire' => 900,
'captcha_path' => 'captcha/',
'captcha_fonts_path' => 'captcha/fonts/5.ttf',
'captcha_width' => 200,
'captcha_height' => 50,
'captcha_font_size' => 14,
'captcha_grid' => false,
'captcha_expire' => 180,
'captcha_case_sensitive' => false,
'use_recaptcha' => false,
'recaptcha_public_key' => '',
'recaptcha_private_key' => '',
'db_table_prefix' => '',
),
),
),
7 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/system/core/Loader.php',
'line' => 975,
'function' => '_ci_init_class',
'class' => 'CI_Loader',
'type' => '->',
'args' =>
array (
0 => 'tank_auth',
1 => '',
2 =>
array (
'website_name' => 'mycom',
'webmaster_email' => 'webmaster#mycom.com',
'phpass_hash_portable' => true,
'phpass_hash_strength' => 8,
'allow_registration' => false,
'captcha_registration' => false,
'email_activation' => false,
'email_activation_expire' => 172800,
'email_account_details' => true,
'use_username' => true,
'username_min_length' => 4,
'username_max_length' => 20,
'password_min_length' => 4,
'password_max_length' => 20,
'login_by_username' => true,
'login_by_email' => true,
'login_record_ip' => true,
'login_record_time' => true,
'login_count_attempts' => true,
'login_max_attempts' => 99,
'login_attempt_expire' => 86400,
'autologin_cookie_name' => 'autologin',
'autologin_cookie_life' => 2592000,
'forgot_password_expire' => 900,
'captcha_path' => 'captcha/',
'captcha_fonts_path' => 'captcha/fonts/5.ttf',
'captcha_width' => 200,
'captcha_height' => 50,
'captcha_font_size' => 14,
'captcha_grid' => false,
'captcha_expire' => 180,
'captcha_case_sensitive' => false,
'use_recaptcha' => false,
'recaptcha_public_key' => '',
'recaptcha_private_key' => '',
'db_table_prefix' => '',
),
3 => NULL,
),
),
8 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/system/core/Loader.php',
'line' => 216,
'function' => '_ci_load_class',
'class' => 'CI_Loader',
'type' => '->',
'args' =>
array (
0 => 'Tank_auth',
1 => NULL,
2 => NULL,
),
),
9 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/system/core/Loader.php',
'line' => 1178,
'function' => 'library',
'class' => 'CI_Loader',
'type' => '->',
'args' =>
array (
0 => 'Tank_auth',
),
),
10 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/system/core/Loader.php',
'line' => 152,
'function' => '_ci_autoloader',
'class' => 'CI_Loader',
'type' => '->',
'args' =>
array (
),
),
11 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/system/core/Controller.php',
'line' => 51,
'function' => 'initialize',
'class' => 'CI_Loader',
'type' => '->',
'args' =>
array (
),
),
12 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/application/libraries/REST_Controller.php',
'line' => 197,
'function' => '__construct',
'class' => 'CI_Controller',
'type' => '->',
'args' =>
array (
),
),
13 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/application/controllers/api/my_project.php',
'line' => 11,
'function' => '__construct',
'class' => 'REST_Controller',
'type' => '->',
'args' =>
array (
),
),
14 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/system/core/CodeIgniter.php',
'line' => 310,
'function' => '__construct',
'class' => 'my_project',
'type' => '->',
'args' =>
array (
),
),
15 =>
array (
'file' => '/Users/charlie/IdeaProjects/my_project/src/index.php',
'line' => 204,
'args' =>
array (
0 => '/Users/charlie/IdeaProjects/my_project/src/system/core/CodeIgniter.php',
),
'function' => 'require_once',
),
),
'previous' => NULL,
))
The rest of the log is similar.It just cant find the Redis class.
Ok,finally I solved it.Just install it with brew:
*brew install --without-apache --with-fpm --with-mysql --with-redis --with-curl --with-intl --with-iconv php72
echo 'export PATH="/usr/local/opt/php#7.2/bin:$PATH"' >> ~/.bash_profile
echo 'export PATH="/usr/local/opt/php#7.2/sbin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile
*
I dont know if these options are right but I did have my php installed properly with all the exts I need.

Referencing field from stdClass Object which contains an array of drawable information

I'd like to return the value of the Birthday field from the following massive mixed array of data containing nested arrays and stdClass Objects. I tried the following code but it didn't work, I would be extremely grateful for any help.
$data->_field_data['nid']['entity']->field_player_birthday['und'][0]['value'];
PHP:
stdClass::__set_state(array(
'node_field_data_field_game_players_nid' => '2931',
'node_title' => '1539634465',
'nid' => '8114',
'node_language' => 'tr',
'field_data_field_player_birthday_node_entity_type' => 'node',
'_field_data' => array (
'node_field_data_field_game_players_nid' => array (
'entity_type' => 'node',
'entity' => stdClass::__set_state(
array( 'vid' => '2931',
'uid' => '1',
'title' => 'Fernando Muslera',
'log' => '',
'status' => '1',
'comment' => '1',
'promote' => '0',
'sticky' => '0',
'ds_switch' => '',
'nid' => '2931',
'type' => 'player',
'language' => 'und',
'created' => '1520727843',
'changed' => '1539137801',
'tnid' => '0',
'translate' => '0',
'revision_timestamp' => '1539137801',
'revision_uid' => '1',
'body' =>
array ( ), 'field_player_address' => array ( 'und' => array ( 0 =>
array ( 'country' => 'AR', 'administrative_area' => 'B',
'sub_administrative_area' => NULL, 'locality' => 'Buenos Aires',
'dependent_locality' => '', 'postal_code' => '', 'thoroughfare' => '',
'premise' => '', 'sub_premise' => NULL, 'organisation_name' => NULL,
'name_line' => NULL, 'first_name' => NULL, 'last_name' => NULL, 'data'
=> NULL, ), ), ), 'field_geofield' => array ( 'und' => array ( 0 => array ( 'geom' => 'POINT (-58.3815591 -34.6036844)', 'geo_type' =>
'point', 'lat' => '-34.603684400000', 'lon' => '-58.381559100000',
'left' => '-58.381559100000', 'top' => '-34.603684400000', 'right' =>
'-58.381559100000', 'bottom' => '-34.603684400000', 'geohash' =>
'69y7pkxfgjdq4', ), ), ), 'field_player_search_news' => array ( ),
'field_player_map' => array ( ), 'field_player_birthday' => array (
'und' => array ( 0 => array ( 'value' => '1986-06-16 00:00:00',
'timezone' => 'America/New_York', 'timezone_db' => 'America/New_York',
'date_type' => 'datetime', ), ), ), 'field_player_team' => array (
'und' => array ( 0 => array ( 'tid' => '328', ), ), ), 'field_image'
=> array ( ), 'field_game_rating' => array ( 'und' => array ( 0 => array ( 'rating' => '90', 'target' => NULL, ), ), ), 'rdf_mapping' =>
array ( 'rdftype' => array ( 0 => 'sioc:Item', 1 => 'foaf:Document',
), 'title' => array ( 'predicates' => array ( 0 => 'dc:title', ), ),
'created' => array ( 'predicates' => array ( 0 => 'dc:date', 1 =>
'dc:created', ), 'datatype' => 'xsd:dateTime', 'callback' =>
'date_iso8601', ), 'changed' => array ( 'predicates' => array ( 0 =>
'dc:modified', ), 'datatype' => 'xsd:dateTime', 'callback' =>
'date_iso8601', ), 'body' => array ( 'predicates' => array ( 0 =>
'content:encoded', ), ), 'uid' => array ( 'predicates' => array ( 0 =>
'sioc:has_creator', ), 'type' => 'rel', ), 'name' => array (
'predicates' => array ( 0 => 'foaf:name', ), ), 'comment_count' =>
array ( 'predicates' => array ( 0 => 'sioc:num_replies', ), 'datatype'
=> 'xsd:integer', ), 'last_activity' => array ( 'predicates' => array ( 0 => 'sioc:last_activity_date', ), 'datatype' => 'xsd:dateTime',
'callback' => 'date_iso8601', ), ), 'path' => array ( 'pathauto' =>
'1', ), 'cid' => '0', 'last_comment_timestamp' => '1520727843',
'last_comment_name' => NULL, 'last_comment_uid' => '1',
'comment_count' => '0', 'name' => 'efet', 'picture' => '0', 'data' =>
'a:7:{s:7:"contact";i:1;s:5:"block";a:1:{s:6:"system";a:1:{s:4:"main";i:1;}}s:16:"ckeditor_default";s:1:"t";s:20:"ckeditor_show_toggle";s:1:"t";s:14:"ckeditor_width";s:4:"100%";s:13:"ckeditor_lang";s:2:"en";s:18:"ckeditor_auto_lang";s:1:"t";}',
)), ), ), 'field_field_player_birthday' => array ( 0 => array (
'rendered' => array ( '#markup' => '1986', '#access' => true, ), 'raw'
=> array ( 'value' => '1986-06-16 00:00:00', 'timezone' => America/New_York', 'timezone_db' => 'America/New_York', 'date_type'
> => 'datetime', ), ), ), ))
You are close (as I've had to change the objects slightly to test, I hope this works)...
echo $data->_field_data['node_field_data_field_game_players_nid']['entity']
->field_player_birthday['und'][0]['value'];
Basically instead of nid, it's node_field_data_field_game_players_nid.

Traversing an nested array and transform some values

I'm looking for a clean solution to transform a nested array.
Here is what I'm trying to achieve...
Original array:
$map = array(
'name' => 'super test',
'machine_name' => 'super_test',
'class' => 'openlayers_map_map',
'options' => array(
'width' => 'auto',
'height' => '300px',
'contextualLinks' => 1,
'provideBlock' => 1,
'view' => array(
'center' => array(
'lat' => '0',
'lon' => '0',
),
'rotation' => '0',
'zoom' => '2',
),
'layers' => array(
'0' => array(
'name' => 'Ma super layer',
'machine_name' => 'plouf',
'class' => 'openlayers_layer_tile',
'options' => array(
'source' => array(
'name' => 'Ma super layer',
'machine_name' => 'plouf',
'class' => 'openlayers_source_osm'
),
'param1' => 'ca roule'
)
),
),
'controls' => array(
'control_mouseposition',
'0' => array(
'name' => 'Control attribution',
'machine_name' => 'openlayers_control_attribution',
'class' => 'openlayers_control_attribution',
'options' => array(
'collapsible' => 1
)
),
'control_rotate',
'control_zoom',
),
'interactions' => array(
'interaction_doubleclickzoom',
'interaction_dragpan',
'interaction_dragrotateandzoom',
'interaction_mousewheelzoom',
),
)
);
Final array:
$map = array(
'name' => 'super test',
'machine_name' => 'super_test',
'class' => 'openlayers_map_map',
'options' => array(
'width' => 'auto',
'height' => '300px',
'contextualLinks' => 1,
'provideBlock' => 1,
'view' => array(
'center' => array(
'lat' => '0',
'lon' => '0',
),
'rotation' => '0',
'zoom' => '2',
),
'layers' => array(
'0' => (object) openlayers_layer_tile
'name' => 'Ma super layer',
'machine_name' => 'plouf',
'class' => 'openlayers_layer_tile',
'options' => array(
'source' => (object) openlayers_source_osm
'name' => 'Ma super layer',
'machine_name' => 'plouf',
'class' => 'openlayers_source_osm'
),
'param1' => 'ca roule'
)
),
),
'controls' => array(
'control_mouseposition',
'0' => (object) openlayers_control_attribution
'name' => 'Control attribution',
'machine_name' => 'openlayers_control_attribution',
'class' => 'openlayers_control_attribution',
'options' => array(
'collapsible' => 1
)
),
'control_rotate',
'control_zoom',
),
'interactions' => array(
'interaction_doubleclickzoom',
'interaction_dragpan',
'interaction_dragrotateandzoom',
'interaction_mousewheelzoom',
),
)
);
Basically, I need to traverse the array, find all children with the 'class' key and transform them into objects of the same name.
If you don't have the classes ready to be instantiated, this code will create anonymous objects instead. (The class name still being present as a property.)
function class_to_object (&$arr) {
if (is_array($arr)) {
foreach ($arr as $key => &$val) {
class_to_object($val);
}
if (isset($arr['class'])) {
$arr = (object) $arr;
}
}
}
class_to_object($map);
Result :
(Notice that the first array is turned into an object, since it contains the field "class" too. I guess you can tweak the function easily enough if you don't want that behavior)
stdClass Object
(
[name] => super test
[machine_name] => super_test
[class] => openlayers_map_map
[options] => Array
(
[width] => auto
[height] => 300px
[contextualLinks] => 1
[provideBlock] => 1
[view] => Array
(
[center] => Array
(
[lat] => 0
[lon] => 0
)
[rotation] => 0
[zoom] => 2
)
[layers] => Array
(
[0] => stdClass Object
(
[name] => Ma super layer
[machine_name] => plouf
[class] => openlayers_layer_tile
[options] => Array
(
[source] => stdClass Object
(
[name] => Ma super layer
[machine_name] => plouf
[class] => openlayers_source_osm
)
[param1] => ca roule
)
)
)
[controls] => Array
(
[0] => stdClass Object
(
[name] => Control attribution
[machine_name] => openlayers_control_attribution
[class] => openlayers_control_attribution
[options] => Array
(
[collapsible] => 1
)
)
[1] => control_rotate
[2] => control_zoom
)
[interactions] => Array
(
[0] => interaction_doubleclickzoom
[1] => interaction_dragpan
[2] => interaction_dragrotateandzoom
[3] => interaction_mousewheelzoom
)
)
)
This totally untested recursive function may get you on the right track:
function recursive_hydrate_array($arr)
{
if(!is_array($arr) || !isset($arr["class"]))
{
throw new Exception("Argument is not an array or does not have a 'class' key.");
}
$klass = $arr["class"];
unset($arr["class"]);
$obj = new $klass();
foreach($arr as $k => $v)
{
if(is_array($arr[$k]) && isset($arr[$k]["class"]))
{
$obj->{$k} = recursive_hydrate_array($arr[$k]);
}
else
{
$obj->{$k} = $arr[$k];
}
}
return $obj;
}
Note that I am making three assumptions here:
The classes in question already exist.
Each class can be instantiated without passing any parameters to its constructor.
All relevant properties of each class are public and can be set from outside of the class.

PHP merge associative arrays by replacing same keys and adding new

I have an array of variable size structured like this (categories is only one of the keys inside data):
print_r($json[123]["data"]["categories"]);
array(
array(
'id' => '2',
'description' => 'Single-player'
),
array(
'id' => '1',
'description' => 'Multi-player'
),
array(
'id' => '9',
'description' => 'Co-op'
),
array(
'id' => '22',
'description' => 'Steam Achievements'
),
array(
'id' => '28',
'description' => 'Full controller support'
)
)
print_r($json[456]["data"]["categories"]);
array(
array(
'id' => '21',
'description' => 'Downloadable Content'
),
array(
'id' => '1',
'description' => 'Multi-player'
)
)
Now, I want to merge these sub-arrays (they can be in variable number) and have all keys added and replaced. I've tried array_merge but it replaces the keys without adding new ones.
In this case I need to obtain this array:
print_r($merged["data"]["categories"]);
array(
array(
'id' => '2',
'description' => 'Single-player'
),
array(
'id' => '1',
'description' => 'Multi-player'
),
array(
'id' => '9',
'description' => 'Co-op'
),
array(
'id' => '22',
'description' => 'Steam Achievements'
),
array(
'id' => '28',
'description' => 'Full controller support'
),
array(
'id' => '21',
'description' => 'Downloadable Content'
)
)
Any help?
Edit:
I think I didn't expressed myself well enough. $json[$id]["data"] has multiple keys I want to merge (categories is just an example). Also the number of $json[$id] keys is variable
Edit2:
The arrays can have duplicate values, and the depth of the keys can be variable. I need to get something like array_merge_recursive() but with same values replaced.
Edit3:
This is the current array. http://pastebin.com/7x7KaAVM I need to merge all keys that have sub-arrays
Try below code:
$json = array(
'123' => array('data' => array('categories' => array(
array(
'id' => '2',
'description' => 'Single-player'
),
array(
'id' => '1',
'description' => 'Multi-player'
),
array(
'id' => '9',
'description' => 'Co-op'
),
array(
'id' => '22',
'description' => 'Steam Achievements'
),
array(
'id' => '28',
'description' => 'Full controller support'
)
))
),
'456' => array('data' => array('categories' => array(
array(
'id' => '21',
'description' => 'Downloadable Content'
)
))
),
);
//print_r($json);
$merged = array();
foreach($json as $j1)
{
foreach($j1 as $j2)
{
foreach($j2 as $key => $j3)
{
foreach($j3 as $j4)
{
$merged[$key][] = $j4;
}
}
}
}
print_r($merged);
Result:
Array
(
[categories] => Array
(
[0] => Array
(
[id] => 2
[description] => Single-player
)
[1] => Array
(
[id] => 1
[description] => Multi-player
)
[2] => Array
(
[id] => 9
[description] => Co-op
)
[3] => Array
(
[id] => 22
[description] => Steam Achievements
)
[4] => Array
(
[id] => 28
[description] => Full controller support
)
[5] => Array
(
[id] => 21
[description] => Downloadable Content
)
)
)
Demo:
http://3v4l.org/X61bE#v430
Try this . To generalize I have added some more arrays.
<?php
$merged_array = array();
$final_array = array();
$json[123]["data"]["categories"] = array(
array(
'id' => '2',
'description' => 'Single-player'
),
array(
'id' => '1',
'description' => 'Multi-player'
),
array(
'id' => '9',
'description' => 'Co-op'
),
array(
'id' => '22',
'description' => 'Steam Achievements'
),
array(
'id' => '28',
'description' => 'Full controller support'
)
);
$json[456]["data"]["categories"] = array(
array(
'id' => '21',
'description' => 'Downloadable Content'
)
);
$json[786]["data"]["categories"] = array(
array(
'id' => '31',
'description' => 'Downloadable Content'
)
);
$json[058]["data"]["categories"] = array(
array(
'id' => '41',
'description' => 'Downloadable Content'
)
);
foreach($json as $key=>$value){
array_push($merged_array,$json[$key]["data"]["categories"]);
}
foreach($merged_array as $value){
foreach($value as $val){
array_push($final_array,$val);
}
}
print_r($final_array);
?>
RESULT
Array
(
[0] => Array
(
[id] => 2
[description] => Single-player
)
[1] => Array
(
[id] => 1
[description] => Multi-player
)
[2] => Array
(
[id] => 9
[description] => Co-op
)
[3] => Array
(
[id] => 22
[description] => Steam Achievements
)
[4] => Array
(
[id] => 28
[description] => Full controller support
)
[5] => Array
(
[id] => 21
[description] => Downloadable Content
)
[6] => Array
(
[id] => 31
[description] => Downloadable Content
)
[7] => Array
(
[id] => 41
[description] => Downloadable Content
)
)

Categories