How to perform Recursion to Nth level? - php

Here is my single database structure.
I have one array which I will export in one file by var_export.
This is a sample array,
return [
'menus' => [
'products' => [
'name' => 'Products',
'link' => 'cctv.html',
'show' => true,
],
'companies' => [
'name' => 'Companies',
'link' => 'companies.html',
'show' => true,
],
],
'products' => [
'section_enabled' => [
'featured_products', 'categories', 'news', 'latest_products', 'case_studies', 'expert_commentary',
'videos', 'companies', 'topics',
],
'pages' => [
'child_category_page' => [
'middle' => [
'left' => [
'class' => 'col-md-9',
'sections' => [
[
'folder' => '',
'element' => 'page_heading',
'variables' => ['page_heading', 'articles'],
],
],
],
],
],
'product_profile_page' => [
'middle' => [
'left' => [
'class' => 'col-md-9',
'sections' => [
[
'folder' => '',
'element' => 'page_heading',
'variables' => ['page_heading'],
],
[
'folder' => 'products',
'element' => 'specifications',
'variables' => ['specifications', 'filters'],
],
],
],
],
],
],
],
'news' => [
'news_types' => [
'expert_commentary' => 'Etary',
'applications' => 'Mon',
'security_beat' => 'SB',
'round_table' => 'RT',
'case_studies' => [
'type' => 'Marcation',
'label' => 'Casies',
],
],
'url_lookup_values' => [
'caudies' => [
'value' => 'Marklication',
'config' => 'castudies',
],
],
],
];
I got the recursion trick from here.
But it doesn't solve my problem.
Here is what I have tried,
function generate_site_config()
{
$data = DB::table("SITE_CONFIGS")->where("parent_id", 0)->get();
$desired_array = [];
get_tree_site_configs($data,$desired_array,0,0);
// file_put_contents(config_path() . DIRECTORY_SEPARATOR . "frontend_configs_demo.php", '<?php return ' . var_export($data, true) . ';');
echo "success";die;
}
function get_tree_site_configs($inputArray, &$outputArray, $parent = 0, $level = 0){
foreach($inputArray as $cc_id => $sub_arr){
if($sub_arr->parent_id == $parent){
$outputArray[] = $sub_arr;
if($sub_arr->variable_value == ''){
$inputArray = DB::table("SITE_CONFIGS")->where("parent_id", $sub_arr->id)->get();
get_tree_site_configs($inputArray, $outputArray, $sub_arr->id, $level + 1);
}else{
pr($sub_arr);
pr($outputArray);die;
}
}
}
}
NOTE: chain will go until variable_value == '', if variable_value found then it stops the tree at that end, then it will look for other parents which are dangling.

Related

Extend an assiociative Array with variable

can someone help me, how I can extend an assiociative array with a variable?
I have a loop (foreach):
foreach($this->getWarehouseListForm() as $wareHouse) {
$wareHouseList[] =
[
"title" => "wareHouse[105]",
"form" => [
"storeId[105]" => [
"type" => "inputText",
"options" => [
"name" => "TSL",
],
],
],
];
}
And I want to extend a object like this:
"sections" => [
[
"title" => 'Schuhe24Assistant.ftpServerTitle',
"description" => 'Schuhe24Assistant.ftpServerDescription',
"form" => [
"ftpServer" => [
'type' => 'text',
'defaultValue' => 'ftp.hisasp2.com',
'options' => [
'name' => 'Schuhe24Assistant.ftpServer',
'required' => true,
]
],
"ftpUser" => [
'type' => 'text',
'defaultValue' => 'username',
'options' => [
'name' => 'Schuhe24Assistant.ftpUser',
'required' => true,
]
],
"ftpPassword" => [
'type' => 'text',
'defaultValue' => 'password',
'options' => [
'name' => 'Schuhe24Assistant.ftpPassword',
#'isPassword' => true,
'required' => true,
],
],
"deleteFiles" => [
'type' => 'toggle',
'defaultValue' => true,
'options' => [
'name' => 'Schuhe24Assistant.deleteFiles',
],
],
],
],
], $wareHouseList
But this code produces nothing (no error output) and the structure check fails in this case. If I remove the variable, the structure check is OK.
Can someone help me out?
Kind regards
Henning
Push your $wareHouseList array into the $sections array in the following ways
$sections['wareHouseList'] = $wareHouseList
It should be working.

Why can't I use my analyzer and get answer 'failed to find analyze'?

I made my index with analyzer like in documentation (there).
This is my index create:
$params = [
'index' => 'mytestindex',
'body' => [
'settings' => [
'analysis' => [
'index_analyzer' => [
'my_index_analyzer' => [
'type' => 'custom',
'tokenizer' => 'standard',
'filter' => [
'lowercase',
'mynGram2'
],
],
],
'search_analyzer' => [
'my_search_analyzer' => [
'type' => 'custom',
'tokenizer' => 'standard',
'filter' => [
'standard',
'lowercase',
'mynGram2'
],
],
],
'filter' => [
'mynGram2' => [
'type' => 'nGram',
'min_gram' => 2,
'max_gram' => 20,
],
],
],
'max_ngram_diff' => 50,
],
],
];
$x = $this->obj->indices()->create($params);
Then i try use my analyzer:
$params = [
'index' => 'mytestindex',
'body' => [
'analyzer' => 'my_search_analyzer',
'text' => 'текст проверить чтобы'
],
];
$x = $this->obj->indices()->analyze($params);
But I get this message:
'{"error":{"root_cause":[{"type":"remote_transport_exception","reason":"[PEREGOVOR2][127.0.0.1:9300][indices:admin/analyze[s]]"}],"type":"illegal_argument_exception","reason":"failed
to find analyzer [my_search_analyzer]"},"status":400}'
So... what am I doing wrong? Why can't I use my analyzer and get answer 'failed to find analyze'?
You're not building your analyzer correctly. You only need one analyzer section in your settings:
$params = [
'index' => 'mytestindex',
'body' => [
'settings' => [
'analysis' => [
'analyzer' => [ <--- change this
'my_index_analyzer' => [
'type' => 'custom',
"tokenizer" => "standard",
'filter' => [
"lowercase",
"mynGram2"
],
],
'my_search_analyzer' => [
"type" => "custom",
"tokenizer" => "standard",
'filter' => [
"standard",
"lowercase",
"mynGram2"
],
],
],
'filter' => [
'mynGram2' => [
"type" => "nGram",
"min_gram" => 2,
"max_gram" => 20,
],
],
],
"max_ngram_diff" => "50",
],
],
];
$x = $this->obj->indices()->create($params);

How to update Amazon CloudFront distribution

I want to update the status of an Amazon CloudFront distribution using the updatedistribution method provided by AWS.
I don't know default value of all the required parameters.
My code is:
list($before, $after) = explode('.', $domain, 2);
$domain_Items = "*." . $after;
$result = $client->updateDistribution([
'DistributionConfig' =>
[
'Aliases' =>
[
'Items' => [$domain_Items, $after],
'Quantity' => 2
],
'CallerReference' => $domain,
'Comment' => 'custom domain for ' . $domain,
'Enabled' => false,
'PriceClass' => 'PriceClass_All',
'CacheBehaviors' => [
'Items' => [
[
'AllowedMethods' =>
[
'CachedMethods' =>
[
'Items' => ['HEAD', 'GET'],
'Quantity' => 2,
],
'Items' => ['HEAD', 'GET', 'OPTIONS', 'PUT', 'POST', 'PATCH', 'DELETE'],
'Quantity' => 7,
],
'Compress' => true,
'DefaultTTL' => 0,
//'FieldLevelEncryptionId' => '<string>',
'ForwardedValues' => [
'Cookies' => [
'Forward' => 'all',
'WhitelistedNames' => [
'Quantity' => 5,
'Items' => ['Host', 'Referer', 'Orign', 'User-Agent', 'HTTP_REFERER'],
],
],
'Headers' =>
[
'Items' => ['Host', 'Referer', 'Orign', 'User-Agent', 'HTTP_REFERER'],
'Quantity' => 5
],
'QueryString' => true,
'QueryStringCacheKeys' => [
'Items' => ['Host', 'Referer', 'Orign', 'User-Agent', 'HTTP_REFERER'],
'Quantity' => 5
],
],
'LambdaFunctionAssociations' => [
'Items' => [
[
'EventType' => 'viewer-request',
'IncludeBody' => true,
'LambdaFunctionARN' => '', //<string>
]
],
'Quantity' => 1,
],
'MaxTTL' => 0,
'MinTTL' => 0,
'PathPattern' => '', //<string>
'SmoothStreaming' => true,
'TargetOriginId' => 'ELB-saglus-test-uat-web-783948842',
'TrustedSigners' => [
'Enabled' => false,
//'Items' => ['<string>'],
'Quantity' => 0,
],
'ViewerProtocolPolicy' => 'redirect-to-https',
],
],
'Quantity' => 1,
],
'DefaultCacheBehavior' =>
[
'AllowedMethods' =>
[
'CachedMethods' =>
[
'Items' => ['HEAD', 'GET'],
'Quantity' => 2,
],
'Items' => ['HEAD', 'GET', 'OPTIONS', 'PUT', 'POST', 'PATCH', 'DELETE'],
'Quantity' => 7,
],
'Compress' => true,
'DefaultTTL' => 0,
'FieldLevelEncryptionId' => '',
'ForwardedValues' =>
[
'Cookies' =>
[
'Forward' => 'all'
],
'WhitelistedNames' => [
'Quantity' => 5,
'Items' => ['Host', 'Referer', 'Orign', 'User-Agent', 'HTTP_REFERER'],
],
'Headers' =>
[
'Items' => ['Host', 'Referer', 'Orign', 'User-Agent', 'HTTP_REFERER'],
'Quantity' => 5,
],
'QueryString' => true,
'QueryStringCacheKeys' => [
'Items' => ['Host', 'Referer', 'Orign', 'User-Agent', 'HTTP_REFERER'],
'Quantity' => 5, // REQUIRED
],
],
'LambdaFunctionAssociations' => [
'Items' => [
[
'EventType' => 'viewer-request',
'IncludeBody' => false,
'LambdaFunctionARN' => '', // REQUIRED <string>
]
],
'Quantity' => 1, // REQUIRED
],
'MaxTTL' => 600,
'MinTTL' => 0,
'SmoothStreaming' => false,
'TargetOriginId' => 'ELB-saglus-test-uat-web-783948842',
'TrustedSigners' =>
[
'Enabled' => false,
'Quantity' => 0
],
'ViewerProtocolPolicy' => 'redirect-to-https'
],
'DefaultRootObject' => '',
'HttpVersion' => 'http2',
'IsIPV6Enabled' => false,
'Logging' => [
'Bucket' => 'saglus-aws-logs.s3.amazonaws.com', // REQUIRED
'Enabled' => true, // REQUIRED
'IncludeCookies' => true, // REQUIRED
'Prefix' => 'logs-for-' . $domain, // REQUIRED
],
'Origins' =>
[
'Items' =>
[
[
'CustomHeaders' =>
[
'Items' =>
[
[
'HeaderName' => 'X-Origin-Verify',
'HeaderValue' => 'cnxpwcausbtobmebhebadbergdifn'
],
],
'Quantity' => 1
],
'CustomOriginConfig' =>
[
'HTTPPort' => 80,
'HTTPSPort' => 443,
'OriginKeepaliveTimeout' => 5,
'OriginProtocolPolicy' => 'http-only',
'OriginReadTimeout' => 120,
'OriginSslProtocols' =>
[
'Items' => ['TLSv1'],
'Quantity' => 1
],
],
'DomainName' => 'saglus-test-uat-web-783948842.us-east-1.elb.amazonaws.com',
'Id' => 'ELB-saglus-test-uat-web-783948842',
'OriginPath' => ''
],
],
'Quantity' => 1,
],
'WebACLId' => '108e7697-00db-4330-8d55-bbe57ca94e44'
],
'Id' => $distribution_id,
'IfMatch' => $ETag,
]);
However, I get the error:
Reference link: updatedistribution in AWS SDK for PHP 3.x
$client = new Aws\CloudFront\CloudFrontClient([
'region' => 'us-east-1',
'version' => 'latest',
'credentials' => [
'key' => $this->AcmKey,
'secret' => $this->AcmSecret
]
]);
// $id = 'E2SYUN95DWJFXC';
$id = $business_custom_data->distribution_id;
try {
$result = $client->getDistribution([
'Id' => $id,
]);
} catch (AwsException $e) {
// output error message if fails
echo $e->getMessage();
echo "\n";
}
$currentConfig = $result["Distribution"]["DistributionConfig"];
$ETag = $result["ETag"];
$distribution = [
'CallerReference' => $currentConfig["CallerReference"], // REQUIRED
'Comment' => $currentConfig["Comment"], // REQUIRED
'DefaultCacheBehavior' => $currentConfig["DefaultCacheBehavior"], // REQUIRED
'DefaultRootObject' => $currentConfig["DefaultRootObject"],
//'Enabled' => $currentConfig["Enabled"], // REQUIRED
'Enabled' => False, // REQUIRED
'Origins' => $currentConfig["Origins"], // REQUIRED
'Aliases' => $currentConfig["Aliases"],
'CustomErrorResponses' => $currentConfig["CustomErrorResponses"],
'HttpVersion' => $currentConfig["HttpVersion"],
'CacheBehaviors' => $currentConfig["CacheBehaviors"],
'Logging' => $currentConfig["Logging"],
'PriceClass' => $currentConfig["PriceClass"],
'Restrictions' => $currentConfig["Restrictions"],
'ViewerCertificate' => $currentConfig["ViewerCertificate"],
'WebACLId' => $currentConfig["WebACLId"],
];
try {
$result = $client->updateDistribution([
'DistributionConfig' => $distribution,
'Id' => $id,
'IfMatch' => $ETag
]);
$status = true;
//var_dump($result);
//die;
} catch (AwsException $e) {
// output error message if fails
echo $e->getMessage();
echo "\n";
}

PHP Recursive Iteration for Nested Array

I have following array, the depth of array cannot be known since array can have n childs.
$menu = [
[
'name' => 'home',
'label' => 'Home',
'uri' => '/home',
'order' => 1,
'attributes' => [
'class' => ['home-class', 'home-class-2'],
'id' => ['home-id']
]
], [
'name' => 'about',
'label' => 'About',
'uri' => '/about',
'order' => 2,
'attributes' => [
'class' => [],
'id' => []
],
'child' => [
[
'name' => 'company_profile',
'label' => 'Company Profile',
'uri' => '/company-profile',
'order' => 1,
'attributes' => [
'class' => [],
'id' => []
]
], [
'name' => 'team',
'label' => 'Team',
'uri' => '/team',
'order' => 2,
'attributes' => [
'class' => ['team-class', 'team-class-2'],
'id' => ['team-id']
],
'child' => [
[
'name' => 'management_team',
'label' => 'Management Team',
'uri' => '/management-team',
'order' => 1,
'attributes' => [
'class' => [],
'id' => []
]
],
[
'name' => 'development_team',
'label' => 'Development Team',
'uri' => '/development-team',
'order' => 2,
'attributes' => [
'class' => [],
'id' => []
]
],
]
],
]
], [
'name' => 'services',
'label' => 'Services',
'uri' => '/services',
'order' => 3,
'attributes' => [
'class' => [],
'id' => []
],
'child' => [
[
'name' => 'web_application',
'label' => 'Web Application',
'uri' => '/web-application',
'order' => 1,
'attributes' => [
'class' => [],
'id' => []
]
], [
'name' => 'mobile_application',
'label' => 'Mobile Application',
'uri' => '/mobile-application',
'order' => 2,
'attributes' => [
'class' => [],
'id' => []
]
], [
'name' => 'cms_development',
'label' => 'CMS Development',
'uri' => '/cms-development',
'order' => 3,
'attributes' => [
'class' => [],
'id' => []
]
],
]
]
];
I want to loop this over and pass data to object, for example.
$nav = new Navigation\Menu('main');
foreach ($menu as $item) {
// Parent element
$navItem = new Navigation\Item($item['name']);
$navItem->setLabel($item['label']);
$navItem->setUri($item['uri']);
$nav->addItem($navItem);
if (isset($item['child']) && is_array($item['child'])) {
// First child
foreach ($item['child'] as $child1) {
$childItem1 = new Navigation\Item($child1['name']);
$childItem1->setLabel($child1['label']);
$childItem1->setUri($child1['uri']);
$navItem->addChild($childItem1);
if (isset($child1['child']) && is_array($child1['child'])) {
// Second child
foreach ($child1['child'] as $child2) {
$childItem2 = new Navigation\Item($child2['name']);
$childItem2->setLabel($child2['label']);
$childItem2->setUri($child2['uri']);
$childItem1->addChild($childItem2);
}
}
}
}
}
This works but with a problem. As you see, I am manually looping over each child, I do not want this, what i am looking for is, It must iterate the array recursively allowing to add any number of child with any depth.
I tried array_walk_recursive or custom recursive function without any result. any pointer to solve this is appreciated.
Thanks.
Here is a little recursive script that should run through every if it is an array or an object, each recursion will return the object. Now this would need some editing for your usage. But it should give you a starting point.
function Navigation($item) {
if (is_object($item)) {
foreach (get_object_vars($item) as $property => $value) {
//If item is an object, then run recursively
if (is_array($value) || is_object($value)) {
$item->$property = Navigation($item);
} else {
$navItem->setLabel($item['label']);
$navItem->setUri($item['uri']);
$nav->addItem($navItem);
}
}
return $nav;
} elseif (is_array($item)) {
foreach ($item as $property => $value) {
//If item is an array, then run recursively
if (is_array($value) || is_object($value)) {
$item[$property] = Navigation($item);
} else {
$navItem->setLabel($item['label']);
$navItem->setUri($item['uri']);
$nav->addItem($navItem);
}
}
return $nav;
}
$navItem->setLabel($item['label']);
$navItem->setUri($item['uri']);
$nav->addItem($navItem);
}
Figured it out finally.
Here is how i did it using custom recursive function.
function recursive($menu, &$nav, $child = false, $parent = null)
{
foreach ($menu as $page) {
$navItem = new Navigation\Item($page['name']);
if (false == $child) {
$nav->addItem($navItem);
} else {
$parent->addChild($navItem);
}
if (isset($page['child'])) {
recursive($page['child'], $nav, true, $navItem);
}
}
}
$nav = new Navigation\Menu('main');
recursive($menu, $nav);

yii2: working with yii2-sitemap-module

i used https://github.com/himiklab/yii2-sitemap-module in my yii2 project
this is my console :
return [
'id' => 'basic-console',
'language' => 'fa-IR',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log', 'gii'],
'controllerNamespace' => 'app\commands',
'modules' => [
'gii' => 'yii\gii\Module',
'user' => [
'class' => 'dektrium\user\Module',
'sourceLanguage' => 'en-US',
'languages' => 'fa-IR'
],
'sitemap' => [
'class' => 'himiklab\sitemap\Sitemap',
'models' => [
// your models
'app\modules\news\models\News',
// or configuration for creating a behavior
[
'class' => 'app\modules\news\models\News',
'behaviors' => [
'sitemap' => [
'class' => SitemapBehavior::className(),
'scope' => function ($model) {
/** #var \yii\db\ActiveQuery $model */
$model->select(['url', 'lastmod']);
$model->andWhere(['is_deleted' => 0]);
},
'dataClosure' => function ($model) {
/** #var self $model */
return [
'loc' => Url::to($model->url, true),
'lastmod' => strtotime($model->lastmod),
'changefreq' => SitemapBehavior::CHANGEFREQ_DAILY,
'priority' => 0.8
];
}
],
],
],
],
'urls' => [
// your additional urls
[
'loc' => '/news/all',
'changefreq' => \himiklab\sitemap\behaviors\SitemapBehavior::CHANGEFREQ_DAILY,
'priority' => 0.8,
'news' => [
'publication' => [
'name' => 'Example Blog',
'language' => 'fa',
],
'access' => 'Subscription',
'genres' => 'Blog, UserGenerated',
'publication_date' => 'YYYY-MM-DDThh:mm:ssTZD',
'title' => 'Example Title',
'keywords' => 'example, keywords, comma-separated',
'stock_tickers' => 'NASDAQ:A, NASDAQ:B',
],
'images' => [
[
'loc' => 'http://example.com/image.jpg',
'caption' => 'This is an example of a caption of an image',
'geo_location' => 'City, State',
'title' => 'Example image',
'license' => 'http://example.com/license',
],
],
],
],
'enableGzip' => true, // default is false
'cacheExpire' => 1, // 1 second. Default is 24 hours
],
],
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
],
'params' => $params,
];
this is my web.php:
'urlManager' => [
'enablePrettyUrl' => TRUE,
'showScriptName' => TRUE,
'enableStrictParsing' => FALSE,
'rules' => [
['pattern' => 'sitemap', 'route' => 'sitemap/default/index', 'suffix' => '.xml'],
// ...
],
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'salt',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
this is my news controller :
use himiklab\sitemap\behaviors\SitemapBehavior;
public function behaviors() {
return [
'sitemap' => [
'class' => SitemapBehavior::className(),
'scope' => function ($model) {
/** #var \yii\db\ActiveQuery $model */
$model->select(['id']);
// $model->andWhere(['is_deleted' => 0]);
},
'dataClosure' => function ($model) {
/** #var self $model */
return [
'loc' => Url::to($model->url, true),
'lastmod' => strtotime($model->lastmod),
'changefreq' => SitemapBehavior::CHANGEFREQ_DAILY,
'priority' => 0.8
];
}
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['get'],
],
],
];
}
Where is my xml file(url)??
What change should I do in my code?
If your controller (sitemap/default/index) is work well.
Your sitemap must be created in root directory via sitemap.xml file name, and accessible from http://your-domain/sitemap.xml URL.
For change it refer to this your code:
'rules' => [
['pattern' => 'sitemap', 'route' => 'sitemap/default/index', 'suffix' => '.xml'],
],
A shorter version of the routing that you can use:
'rules' => [
'sitemap.xml' => 'sitemap/default/index',
And relative to this route url in web: http://website/sitemap.xml
However, you can generate a sitemap without any extensions, which simplifies your work and does not need to understand other people's code. To do this, simply create the controller as in my working example:
<?php
namespace frontend\controllers;
use frontend\models\blog\articles\BlogArticles;
use frontend\models\blog\categories\BlogCategories;
use frontend\models\blog\series\BlogSeries;
use frontend\models\blog\tags\BlogTags;
use yii\web\Controller;
use yii\db\Query;
use Yii;
class SitemapController extends Controller
{
public function actionIndex()
{
//if You want delete cache
// Yii::$app->cache->delete('sitemap');
if (!$xml_sitemap = Yii::$app->cache->get('sitemap')) { // if has cache sitemap
$urls = array();
// all my categories
$articles = BlogArticles::find()->active()->orderCreatedAt()->all();
foreach ($articles as $article) {
$urls[] = array(
'loc' => $article->url,
'lastmod' => date( DATE_W3C, strtotime($article->lastMod) ),
'changefreq' => 'daily',
'priority' => 1.0
);
}
$categories = BlogCategories::find()->orderId()->all();
foreach ($categories as $category) {
$urls[] = array(
'loc' => $category->url,
'changefreq' => 'weekly',
'priority' => 0.8
);
}
$series = BlogSeries::find()->orderId()->all();
foreach ($series as $sery) {
$urls[] = array(
'loc' => $sery->url,
'changefreq' => 'weekly',
'priority' => 0.5
);
}
$tags = BlogTags::find()->orderId()->all();
foreach ($tags as $tag) {
$urls[] = array(
'loc' => $tag->url,
'changefreq' => 'weekly',
'priority' => 0.4
);
}
$xml_sitemap = $this->renderPartial('index', array(
'host' => Yii::$app->request->hostInfo, // your current domain
'urls' => $urls, // с generate urls for sitemap
));
Yii::$app->cache->set('sitemap', $xml_sitemap, 60*60*12); //cache 12 h
}
Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
echo $xml_sitemap;
}
}
And You can see result in live site: https://coderius.biz.ua/sitemap.xml

Categories