I currently have an array that holds an array of arrays:
array(9) {
["enabled"]=>
array(4) {
["title"]=>
string(14) "Enable/Disable"
["type"]=>
string(8) "checkbox"
["label"]=>
string(25) "Enable"
["default"]=>
string(3) "yes"
}
["title"]=>
array(5) {
["title"]=>
string(5) "Title"
["type"]=>
string(4) "text"
["description"]=>
string(60) "This controls the title which the user sees during checkout."
["default"]=>
string(18) "Retail Finance"
["desc_tip"]=>
bool(true)
}
This array is called $test. Now as you can see in this array there's an array called "enabled" at index 0, and an array called "title" at index 1. I'd like to splice another associative array between index 0 and 1. I've included this below:
'enable_finance_calculator' => array(
'title' => __( 'Enable Calculator', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Enable Finance Calculator', 'woocommerce' ),
'default' => 'yes'
),
Normally when doing this I'd use array_splice(), but this does not handle associative arrays. What is the best option here?
Kind of involved but you can slice and merge:
$test = array_merge(
array_slice($test, 0, $pos=array_search('enabled', array_keys($test), true)+1, true),
$newarray,
array_slice($test, $pos, NULL, true)
);
Search on the array keys to find the position and slice up to that
Merge with the new array
Merge with a slice from the position up to the end of the array
You should be able to do this (haven't tested it):
// Get first item off from index 0
$tempData = array_shift($data);
// Add new array $newData at index 0
array_unshift($data, $newData);
// Add old data again at index 0, rest of items should get an incremented index, so $newData is at 1 and ['title'] is at 2
array_unshift($data, $tempData);
Related
I have data as below:
Array
(
'action' => 'Buy',
'barcode' => '8993200661336',
'price' => 9000,
'intCode' => '30209423',
'quantity' => 1,
'promoDiscount' => Array
(
0 => Array
(
'promoId' => 'P00722000091',
'percentage' => 10,
'amount' => 900,
),
1 => Array
(
'promoId' => 'P00221000044',
'percentage' => 10,
'amount' => 900,
),
),
);
In Array promoDiscount value insert to different table, into 2 rows of data. if I insert intCode into the table, the value only goes to array index [0], while for array index[1] the result is offset.
how to insert intCode into index array[0] & index array[1] ?
If I understood correctly, you simply want to move the same intCode value inside the sub-arrays of promoDiscount.
You just need to add the additional parameter, looping either with for or foreach to make it dynamic. Like this:
<?php
foreach ($array['promoDiscount'] as $key => $val) {
$array['promoDiscount'][$key]['intCode'] = $array['intCode'];
}
?>
This will change your array to
["action"]=>
string(3) "Buy"
["barcode"]=>
string(13) "8993200661336"
["price"]=>
int(9000)
["intCode"]=>
string(8) "30209423"
["quantity"]=>
int(1)
["promoDiscount"]=>
array(2) {
[0]=>
array(4) {
["promoId"]=>
string(12) "P00722000091"
["percentage"]=>
int(10)
["amount"]=>
int(900)
["intCode"]=>
string(8) "30209423"
}
[1]=>
array(4) {
["promoId"]=>
string(12) "P00221000044"
["percentage"]=>
int(10)
["amount"]=>
int(900)
["intCode"]=>
string(8) "30209423"
}
}
}
Let's call your array $array
$array['promoDiscount'] [0] ['intCode'] = 'yourValue'
$array['promoDiscount'] [1] ['intCode'] = 'yourValue'
Or you can use for loop for
$array['promoDiscount']
How to foreach through a deeper array in PHP? I want to approach 'price' and list all prices below each other.
$addons = get_product_addons($product->get_id());
When I VAR_DUMP the $addons var, it outputs the below.
array(1) {
[0]=>
array(7) {
["name"]=>
string(8) "Afmeting"
["description"]=>
string(0) ""
["type"]=>
string(6) "select"
["position"]=>
int(0)
["options"]=>
array(10) {
[0]=>
array(5) {
["label"]=>
string(8) "70 x 200"
["price"]=>
string(0) "70.00"
["min"]=>
string(0)""
...
So I want to output this result:
70.00
60.00
Etcetera.. *All prices
I guess that piece of code is what you are looking for:
foreach($addons as $addon)
{
echo $addon["options"]["price"].PHP_EOL;
}
You do not need to use foreach to access nested elements of array. Just use it's key.
PHP_EOL is a constant containing newline for your OS. For web application use special formatting suitable for your page (<br> e.g.)
You can walk or foreach through the items:
<?php
$data =
[
[
'name' => 'orange',
'options' =>
[
'price' => '6.00'
]
],
[
'name' => 'banana',
'options' =>
[
'price' => '4.00'
]
]
];
array_walk($data, function($v) {
echo $v['options']['price'], "\n";
});
Output:
6.00
4.00
Or you could create an array of prices and iterate on that (here using short function syntax):
$prices = array_map(fn($v)=>$v['options']['price'], $data);
var_export($prices);
Output:
array (
0 => '6.00',
1 => '4.00',
)
i have a question about these 2 ways of declaring the array (I thought they would be the same):
$result[$zone->id]['activities'][$activity->id] = array(
'title' => $activity->title,
'image' => $activity->image
);
$result[$zone->id]['activities'] = array(
$activity->id => array(
'title' => $activity->title,
'image' => $activity->image
)
);
So my goal is to provide an array that is sorted by the Zone then by it's activities listed under the array of "activities".
The first array gives me the following result which is correct for my example:
array(3) {
[5]=>
array(2) {
["title"]=>
string(15) "Oftalmologistas"
["image"]=>
string(28) "logotipo_1575907014_4232.png"
}
[6]=>
array(2) {
["title"]=>
string(7) "Óticas"
["image"]=>
string(28) "logotipo_1575907021_1130.png"
}
[7]=>
array(2) {
["title"]=>
string(21) "Outras especialidades"
["image"]=>
string(28) "logotipo_1575907034_8988.png"
}
}
But the second array gives me the last activity found and replaces the two above it doesn't add them to array instead it replaces them.
array(1) {
[7]=>
array(2) {
["title"]=>
string(21) "Outras especialidades"
["image"]=>
string(28) "logotipo_1575907034_8988.png"
}
}
My goal here is to understand the diference syntax between them why the first adds them to array while the seconds replaces. Also any other way of declaring the array to the same first value. Thanks in advance!
this is just simple nested arrays with different keys and values for better understanding i change it to this code:
$result[100]['activities'][200] = array(
'title' => 4000,
'image' => 3000
);
$result[300]['product'] = array(
444444=> array(
'title' => 5000,
'image' => 6000
)
);
echo '<pre>';
var_dump($result);
first we have two array and inside each of them again there is another two arrays with different key and values if you look at this picture i uploaded i think you can understand completely.
nested array result
for first example
$result[$zone->id]['activities'][$activity->id] = array(
'title' => $activity->title,
'image' => $activity->image
);
You are assigning value to key "$activity->id"
Here as id gone be dynamic it will create new key everytime.
In second example
$result[$zone->id]['activities'] = array(
$activity->id => array(
'title' => $activity->title,
'image' => $activity->image
)
);
You are assiging value/array to activities.
So every time you try to assign value to activities key it will
replace it.
i want to edit a script i found online. is has an hardcoded array like this.
$servers = array(
'Google Web Search' => array(
'ip' => '',
'port' => 80,
'info' => 'Hosted by The Cloud',
'purpose' => 'Web Search'
),
'Example Down Host' => array(
'ip' => 'example.com',
'port' => 8091,
'info' => 'ShittyWebHost3',
'purpose' => 'No purpose'
)
);
Result:
array(2) {
["Google Web Search"]=>
array(4) {
["ip"]=>
string(0) ""
["port"]=>
int(80)
["info"]=>
string(19) "Hosted by The Cloud"
["purpose"]=>
string(10) "Web Search"
}
["Example Down Host"]=>
array(4) {
["ip"]=>
string(11) "example.com"
["port"]=>
int(8091)
["info"]=>
string(14) "ShittyWebHost3"
["purpose"]=>
string(10) "No purpose"
}
}
I put this data in a database and want to make the same array but i dont seem to get it working
This is the code i added to make an array:
$query ="SELECT name, ip, port, hosting FROM sites";
$select = $conn->prepare($query);
$select->execute(array());
$testing = array();
while($rs = $select->fetch(PDO::FETCH_ASSOC)) {
$testing[] = array($rs['name'] => array('ip'=> $rs['ip'], 'port'=> $rs['port'], 'hosting'=> $rs['hosting']));
}
The result from this is:
array(2) {
[0]=>
array(1) {
["Google Web Search"]=>
array(3) {
["ip"]=>
string(10) "google.com"
["port"]=>
string(2) "80"
["hosting"]=>
string(19) "Hosted by The Cloud"
}
}
[1]=>
array(1) {
["Example Down Host"]=>
array(3) {
["ip"]=>
string(11) "example.com"
["port"]=>
string(2) "09"
["hosting"]=>
string(14) "ShittyWebHost3"
}
}
}
is there a way to make the bottom array the same as the top array, i dont want to edit the whole script, this seems easier.
You are appending a new integer indexed element with [] and then adding 2 nested arrays. Instead, add the name as the key:
$testing[$rs['name']] = array('ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']);
Since you specify the columns in the query and they are the same as the array keys, then just this:
$testing[$rs['name']] = $rs;
When you assign a value to an array you use the syntax $arr[key] = $value. If you omit the key during the assignment, $value will be assigned to the next available integer key of the array, starting from 0.
This is an example of how it works:
$arr = array();
$arr[] = 'one';//Empty, so insert at 0 [0=>'one']
$arr[] = 'two';//Last element at 0, so use 1 [0=>'one',1=>'two']
$arr[6]= 'three';//Key is used, so use key [0=>'one',1=>'two',6=>'three']
$arr[] = 'four';//Max used integer key is 6, so use 7
print_r($arr);//[0=>'one',1=>'two',6=>'three',7=>'four']
So, when in your code you are using
$testing[] = array(
$rs['name'] => array(
'ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']
)
);
You are assigning the newly created array to the positions 0,1,2,..N.
To avoid this, just specify the key explicitly, using the value you really want, like
$testing['name'] => array(
'ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']
);
You can read more about arrays in the documentation
Side note
If you don't mind having an extra column in the generated arrays, you can rewrite entirely your code this way:
$query ="SELECT name, ip, port, hosting FROM sites";
$results = $conn->query($query)->fetchAll(PDO::FETCH_ASSOC);
$testing = array_column($results,null,'name');
It's slightly slower, but very handy in my opinion, PDOStatement::fetchAll retrieves all the data at once and array_column using null as second parameter does reindex the array with the wanted column as key.
PDOStatement::fetchAll
array_column
I have two arrays that i want to compare their structure i.e, same keys.
I tried using array_diff_key but the problem is that one array is defined like this:
$fields = array('id' , 'site', 'placement', 'device', 'source', 'campaign', 'url', 'country', 'dof_count', 'dof_idx', 'active');
so when i use var_dump() on it i get this result:
{
[0]=>
string(2) "id"
[1]=>
string(4) "site"
[2]=>
string(9) "placement"
[3]=>
string(6) "device"
[4]=>
string(6) "source"
[5]=>
string(8) "campaign"
[6]=>
string(3) "url"
[7]=>
string(7) "country"
[8]=>
string(9) "dof_count"
[9]=>
string(7) "dof_idx"
[10]=>
string(6) "active"
}
and the other is created by a function and comes back like this:
{
["id"]=>
NULL
["site"]=>
NULL
["placement"]=>
NULL
["device"]=>
NULL
["source"]=>
NULL
["campaign"]=>
NULL
["url"]=>
NULL
["country"]=>
NULL
["dof_count"]=>
int(0)
["dof_idx"]=>
NULL
["active"]=>
NULL
}
so while the two arrays have the same structure, array_diff_key won't help. is there a way in php to compare this two array's structure while ignoring the content, which in my case it's all the null's and the one int in the second array?
You can simply use array_diff along with array_keys as
$result = array_diff($fields,array_keys($keys_array));
Note : Not Tested
I saw the other answers and for all I know they are correct. Those functions will be able to help you out.
But I couldn't understand why would you create your array like this:
$fields = array('id' , 'site', 'placement', 'device', 'source', 'campaign', 'url', 'country', 'dof_count', 'dof_idx', 'active');
If your objective was to simply verify the other array all along, then simply associatively create it:
<?php
$fields = array(
'id' => null,
'site' => null,
'placement' => null,
/*...*/
'active' => null
);
But still, I don't understand your need to verify the array structure, given that it should always be the same. If you have more than one input type for the array's then you should create a field called type on all of the arrays you are going to return and "if" them from there.
Example:
<?php
/*This array has a type and only two indexes of data.*/
$inputArray = array(
'type' => 'firstType',
'data1' => 'data',
'data2' => 'data'
);
/*This array also has a type but 6 indexes containing datas*/
$anotherInputArray = array(
'type' => 'secondType',
'data3' => 'data',
'data4' => 'data',
'data4' => 'data',
'data4' => 'data',
'data4' => 'data',
'data4' => 'data'
);
treatArray($inputArray);
treatArray($anotherInputArray);
function treatArray($array){
if($array['type']=='firstType'){
/*Treat it in one way*/
}elseif($array['type']=='secondType'){
/*Or the other way*/
}
}
I hope I could help, but you didn't describe the context you are working with, so I did my best to guess arround (even though it is not recommended).
Just array_flip your $field array:
var_dump(array_diff_key(array_flip($fields), $array2));