Push array in another multidimensional array - php

I am trying to add values in a multidimensional array. Given below is how its supposed to be
array(
'name' => 'Hotel',
'placeholder' => 'Select the hotel',
'id' => $prefix . 'confirmation_hotel',
'type' => 'select_advanced',
'multiple' => false,
'options' => array(
'5896' => 'Hotel 1',
'6005' => 'Hotel 2'
)
),
But I getting data of options from a custom function with a foreach loop, given below is the code.
global $bookyourtravel_accommodation_helper, $bookyourtravel_car_rental_helper;
$items = $order->get_items();
$names = array();
foreach ( $items as $item_id => $item ) {
$bookyourtravel_theme_woocommerce = BookYourTravel_Theme_WooCommerce::get_instance();
$bookyourtravel_theme_woocommerce->init();
$order_names = $bookyourtravel_theme_woocommerce->order_item_name_confirmation($item);
}
$order_names output:
array(2) {
["name"]=>
string(17) "Hotel 1"
["id"]=>
string(4) "5896"
}
array(2) {
["name"]=>
string(26) "Hotel 2"
["id"]=>
string(4) "6005"
}
Now I need to add this data in the array given above. I'm not sure how to achieve this, can someone help me.

In the loop, after $order_names assignment, add :
$originalArray['options'][$order_names['id']] = $order_names['name'];

I assume your first array at the top is called $a.
So you can append an array element to your 'options' sub array like this:
foreach ($order_names as $order_name) {
array_push($a['options'], array($order_name['id'] => $order_name['name']));
}

Related

Multi-dimentional array how to get the nested value without foreach loop

I got output from one of the WordPress table cells. The following value is displayed.
$allcoinkey=get_option('_transient_mcw-custom-data');
var_dump($allcoinkey);
and the output:
[0]=>
array(2) {
["slug"]=>
string(7) "bitcoin"
["keywords"]=>
string(30) "بیتکوین,بیت کوین"
}
[1]=>
array(2) {
["slug"]=>
string(8) "ethereum"
["keywords"]=>
string(27) "اتریوم,اتاریوم"
}
}
How do I access keyword values where slug=bitcoin without foreach?
i use this sample code:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
You can do it like this:
<?php
$allcoinkey = [
[
'slug' => 'bitcoin',
'keywords' => 'بیتکوین,بیت کوین',
],
[
'slug' => 'ethereum',
'keywords' => 'اتریوم,اتاریوم',
],
];
$bitcoinKeywords = current(array_filter($allcoinkey, static function (array $cryptoCurrency) {
return $cryptoCurrency['slug'] === 'bitcoin';
}))['keywords'];
echo $bitcoinKeywords;

Compare multidimensional array with each other and some array field with external variable

I have an array like below. I need to compare with each other and return the matching array on the first index and followed by other.
How can we compare whole array each other based on id and scid with $scid?
$scid = 307;
$array = array(
0 =>
array(
'id' => '485',
'scid' => 306
),
1 =>
array(
'id' => '484',
'scid' => null
),
2 =>
array(
'id' => '486',
'scid' => 305
),
3 =>
array(
'id' => '485',
'scid' => 307
),
4 =>
array(
'id' => '485',
'scid' => 309
),
5 =>
array(
'id' => '485',
'scid' => 329
),
);
The result array should be like
array(3) {
[485]=> array(2) { ["id"]=> string(3) "485" ["scid"]=> int(307) }
[484]=> array(2) { ["id"]=> string(3) "484" ["scid"]=> NULL }
[486]=> array(2) { ["id"]=> string(3) "486" ["scid"]=> int(305) }
}
If array has duplicate id on which scid is not matching then we can pick any id value.
Note :The matching sub array should always be the first index of resulting array.An amount will always be unique and might contain null as well in array.
You want something like this?
$result = [];
foreach ($array as $item) {
$result[$item['id']] = ['id' => $item['id'], 'scid' => $item['scid']];
}
var_dump($result);
Try this,
$temp = [];
foreach($array as $k => $v){
$temp[$v['id']][] = $v;
}
Give it a try, this will work.

Can't declare keys in two dimensional array in PHP

When i try to generate array, like this way:
$files_array = array(
'name' => array(),
'path' => array()
);
and then assign them values:
$files_array['name'][] = $fileinfo->getFilename();
$files_array['path'][] = $pathname;
the var_dump() function return me an array with numeric keys instead of "name" and "path", like this:
array(2) { [0]=> array(0) { } [1]=> array(0) { } }
What's wrong with the array? I've tried several way of doing this, but none give me my desired array.
EDIT:
A filled array dump, with the same code:
array(2) { [0]=> array(3) { [0]=> string(44) "./upload/4//lol/Nuovo documento di testo.TXT" [1]=> string(51) "./upload/4//lol/blue_bokeh_4-wallpaper-1366x768.jpg" [2]=> string(29) "./upload/4//lol/menny €.txt" } [1]=> array(3) { [0]=> string(28) "Nuovo documento di testo.TXT" [1]=> string(35) "blue_bokeh_4-wallpaper-1366x768.jpg" [2]=> string(13) "menny €.txt" } }
EDIT:
My full code
$files_array = array(
'name' => array(),
'path' => array()
);
$fileinfos = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootpath)
);
foreach ($fileinfos as $pathname => $fileinfo) {
if (!$fileinfo->isFile())
continue;
$files_array['name'][] = $fileinfo->getFilename();
$files_array['path'][] = $pathname;
}
That's how it works:
<?php
$files_array = array();
$i = 0;
$files_array[$i]['name'] = $fileinfo->getFilename();
$files_array[$i]['path'] = $pathname;
$i++;
The result output will be like:
array (size=2)
0 =>
array (size=2)
'name' => string 'file' (length=4)
'path' => string '/foo/' (length=5)
1 =>
array (size=2)
'name' => string 'file2' (length=5)
'path' => string '/bar/' (length=5)
I would suggest reading the php manual on arrays. Here are some examples.
//1
$files_array = array();
$files_array['name'] = array();
$files_array['path'] = array();
//2
$files_array = array(
'name' => [],
'path' => []
);

PHP Possible to move an multidimensional array element to another specific spot?

I am trying to figure out how I can move an array element to another spot. Is this possible?
Here is my example the var_dump array:
array
'person' =>
array
'first_name' =>
array
'...'
'last_name' =>
array
'...'
'rank' =>
array
'...'
'score' =>
array
'...'
'item' =>
array
'...'
'work' =>
array
'company' =>
array
'...'
'phone' =>
array
'...'
And of course there are values in the '...', but just to simplify it. So I need to move "score" before "rank", so the output will show score first before rank, is that possible?
Now I know the array push/pop/shift/unshift but none of those would help me here I think.
Please note, I have no control of this array...I am receiving it as is...
basically it is coming from a Wordpress plugin and it has a filter for these fields so I am using this to catch it.
add_filters( 'work_rank_fields', 'custom_order');
function custom_order($fields) {
var_dump($fields); //what you see on top
}
Using a sample array like you gave us, you could try something like this.
$sample = array(
'person' => array(
'first_name' => array('first'),
'last_name' => array('last'),
'rank' => array('rank'),
'score' => array('score'),
'item' => array('item')
),
'work' => array(
'company' => array('company'),
'phone' => array('phone')
)
);
function reorder_person( $sample )
{
extract( $sample['person'] );
// the desired order below for the keys
$sample['person'] = compact('first_name','last_name','score','rank','item');
return $sample;
}
$sample = reorder_person( $sample );
Now your var_dump of $sample should display score before rank
array(2) {
'person' =>
array(5) {
'first_name' =>
array(1) {
[0] =>
string(5) "first"
}
'last_name' =>
array(1) {
[0] =>
string(4) "last"
}
'score' =>
array(1) {
[0] =>
string(5) "score"
}
'rank' =>
array(1) {
[0] =>
string(4) "rank"
}
'item' =>
array(1) {
[0] =>
string(4) "item"
}
}
'work' =>
array(2) {
'company' =>
array(1) {
[0] =>
string(7) "company"
}
'phone' =>
array(1) {
[0] =>
string(5) "phone"
}
}
}
A little clumsy but, your wordpress filter custom_order function then might look like:
function custom_order( $fields ) {
$a = array();
foreach( $fields['person'] as $key => $value )
{
if ( $key == 'rank' ) continue; // wait until we get score first
if ( $key == 'score' )
{
$a['score'] = $value; // add score first, then rank
$a['rank'] = $fields['person']['rank'];
continue;
}
$a[$key] = $value;
}
$fields['person'] = $a;
return $fields;
}
I'm not sure which is the order criteria but I guess one of this functions can help you. Take a look particularly to last three. You just have to create the appropriate comparison function

zend form Issue in zend framework

I am using zend Framework Form,
I am newbie in zend Framework and i want to display my check box form like this :-
*SK336
*CP
*PES
*JCP
*BGH
*SK996
*KO
*RTY
*HGR
*SK547
*GPK
*SK478
*JUP
Note where :- * is check-box here
what i am trying is here :-
public function init()
{
$parents = array();
$childs = array();
foreach ($this->Tagkey as $aResultDataValue) {
$parents [$aResultDataValue['parent']] = $aResultDataValue['parent'];
$childs [$aResultDataValue['parent']][] = $aResultDataValue['child'];
}
foreach ($parents as $parent){ // print_r ($parents); die();
$tags = new Zend_Form_SubForm();
$tags->addElements(array(
new Zend_Form_Element_MultiCheckbox('parent', array(
'multiOptions' => array($parent),
'filters' => array('StringTrim'),
'validators' => array(
array('InArray',
false,
array($parent))
)
)),
));
foreach ($childs as $child){
$tags->addElements(array(
new Zend_Form_Element_MultiCheckbox('child', array(
'multiOptions' => array($child),
'filters' => array('StringTrim'),
'validators' => array(
array('InArray',
false,
$child)
)
)),
));
}
$this->addSubForms(array(
'tags' => $tags,
)
);
}
I am able to create such type of structure in any .php page but not able to do that right now in zend framework form, I am using zend sub-form here.
Also I got an error right now when i am using this query
Warning: htmlspecialchars() expects parameter 1 to be string, array given in /var/www/dashboard_campaign/library/Zend/View/Abstract.php on line 905
More Information about my Question :-
(1) mysql qyery
select b.tagCode parent,a.tagCode child from tag a, tag b where a.tagParentId=b.tagId
(2) output of Zend_Debug::dump($this->Tagkey);
array(9) {
[0] => array(2) {
["parent"] => string(5) "SK336"
["child"] => string(2) "CP"
}
[1] => array(2) {
["parent"] => string(5) "SK336"
["child"] => string(3) "PES"
}
[2] => array(2) {
["parent"] => string(5) "SK336"
["child"] => string(3) "JCP"
}
[3] => array(2) {
["parent"] => string(5) "SK996"
["child"] => string(2) "KO"
}
[4] => array(2) {
["parent"] => string(5) "SK996"
["child"] => string(3) "RTY"
}
[5] => array(2) {
["parent"] => string(5) "SK996"
["child"] => string(3) "HGR"
}
[6] => array(2) {
["parent"] => string(5) "SK547"
["child"] => string(3) "GPK"
}
[7] => array(2) {
["parent"] => string(5) "SK478"
["child"] => string(3) "JUP"
}
[8] => array(2) {
["parent"] => string(5) "SK336"
["child"] => string(3) "BGH"
}
}
Now i can understand your problem. I think it is to hard for handle that think from sub form. Try to use zend view scripts as following way.
Your form.php
public function init()
{
foreach ($parents as $parent) {
$parent = new Zend_Form_Element_Hidden($parent);
$parent->setDecorators(array(
array(
'ViewScript',
array(
'viewScript' => 'customviewscripts/parent.phtml',
'parent' => $parent
)
)
);
$this->addElement($parent);
}
}
file at views/script/customviewscript/parent.phtml
<?php
$params = $this->element->getDecorator('ViewScript')->getOptions();
$parent = $parems['parent'];
$string = '<label>$parent['name']</label><input type="check" name="parent[]">';
foreach ($children as $child) {
$string .= <label>$child['name']</label>
. <input type="check" name=child[$parent[id]][]>' ;
}
print $string;
?>
This is not the real solution. I percent only example. I think you can customize that. Most of developer use view script to make complex forms.
Your looking like mentioned wrong syntax for multi options John, you should try this.
Remove array for $parent see example below.
new Zend_Form_Element_MultiCheckbox('parent', array(
'multiOptions' => $parent,
'filters' => array('StringTrim'),
'validators' => array(
array('InArray',
false,
array($parent))
)
From db results you have to produce following type of array for the $parent variable
$parent variable should like this for example copy this array and try your self without fetching from database,you will see
all options
$parent=Array ([1] => blah1 [2] => blah2 [3] => blah3 [4] => blah4 [5] => blah5);
Check this one also for multiple check boxes, in place of array you should try placing array variable, I havn't tried this just looked at internet but should work fine.
$category1 = new Zend_Form_Element_MultiCheckbox('categories',Array())
$category1->setLabel('Category 1');
$category2 = new Zend_Form_Element_MultiCheckbox('categories',Array())
$category2->setLabel('Category 2');
... later...
$this->addElement($category1)
->addElement($category2);

Categories