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));
Related
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 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);
I'm trying to get an array to output in a key and value format. When I use the second style shown below it works fine, but when I use the first style I don't get the same results. I think something is different in how the keys are used but I'm not entirely sure.
So, is there any difference between building an array like this:
$featured = get_post_meta($profileID, 'profile_featured', true);
if ($featured == '1'){$my_fake_pages["featured"] = "Featured";};
$celebs = get_post_meta($profileID, 'profile_celebs', true);
if ($celebs== '1'){$my_fake_pages["coversandcelebrities"] = "Covers & Celebrities";};
$fashion = get_post_meta($profileID, 'profile_fashion', true);
if ($fashion == '1'){$my_fake_pages["fashion"] = "Fashion";};
$beauty = get_post_meta($profileID, 'profile_beauty', true);
if ($beauty == '1'){$my_fake_pages["beauty"] = "Beauty";};
$advertising = get_post_meta($profileID, 'profile_advertising', true);
if ($advertising == '1'){$my_fake_pages["advertising"] = "Advertising";};
$bio = get_post_meta($profileID, 'profile_bio', true);
if ($bio == '1'){$my_fake_pages["bio"] = "Bio";};
and writing one like this:
$my_fake_pages = array(
'featured' => 'Featured',
'coversandcelebrities' => 'Covers & Celebrities',
'fashion' => 'Fashion',
'beauty' => 'Beauty',
'advertising' => 'Advertising',
'bio' => 'Bio'
);
Thanks in advance.
** To be clear, I know one is conditional and the other isn't. What I'm wanting to know is if the output style of the first example is equivalent to that of the second, where the key is the index of the array rather than a number being the index, and the value is still the value.
They are the same. To prove it, I've simplified your code and compared the two generated arrays
<?php
$a["featured"] = "Featured";
$a["coversandcelebrities"] = "Covers & Celebrities";
$a["fashion"] = "Fashion";
$a["beauty"] = "Beauty";
$a["advertising"] = "Advertising";
$a["bio"] = "Bio";
$b = array(
'featured' => 'Featured',
'coversandcelebrities' => 'Covers & Celebrities',
'fashion' => 'Fashion',
'beauty' => 'Beauty',
'advertising' => 'Advertising',
'bio' => 'Bio'
);
$same = !array_diff($a, $b) && !array_diff($b, $a);
var_dump($a);
var_dump($b);
echo "<br>Same = $same";
This outputs:
array(6) { ["featured"]=> string(8) "Featured" ["coversandcelebrities"]=> string(24) "Covers & Celebrities" ["fashion"]=> string(7) "Fashion" ["beauty"]=> string(6) "Beauty" ["advertising"]=> string(11) "Advertising" ["bio"]=> string(3) "Bio" }
array(6) { ["featured"]=> string(8) "Featured" ["coversandcelebrities"]=> string(24) "Covers & Celebrities" ["fashion"]=> string(7) "Fashion" ["beauty"]=> string(6) "Beauty" ["advertising"]=> string(11) "Advertising" ["bio"]=> string(3) "Bio" }
Same = 1
The if() version only adds to the array if the conditions are met. the second one adds everything, unconditionally. that has nothing to do with the keys.
It's the difference between going to the grocery store with a shopping list and only getting what's on the list, and going to the store and buying 1 of everything.
If i understand your question right, you want to know if building an array like this:
$my_fake_pages["featured"] = "Featured";
$my_fake_pages["coversandcelebrities"] = "Covers & Celebrities";
$my_fake_pages["fashion"] = "Fashion";
$my_fake_pages["beauty"] = "Beauty";
$my_fake_pages["advertising"] = "Advertising";
$my_fake_pages["bio"] = "Bio";
is any different than building it like this:
$my_fake_pages = array(
'featured' => 'Featured',
'coversandcelebrities' => 'Covers & Celebrities',
'fashion' => 'Fashion',
'beauty' => 'Beauty',
'advertising' => 'Advertising',
'bio' => 'Bio'
);
The answer is no. Both generate an associative array (instead of a numbered array) like this:
array(6) {
["featured"]=>
string(8) "Featured"
["coversandcelebrities"]=>
string(24) "Covers & Celebrities"
["fashion"]=>
string(7) "Fashion"
["beauty"]=>
string(6) "Beauty"
["advertising"]=>
string(11) "Advertising"
["bio"]=>
string(3) "Bio"
}
And also since PHP 5.4.x you can have a "short syntax" array generation like this (notice the []):
$my_fake_pages = [
'featured' => 'Featured',
'coversandcelebrities' => 'Covers & Celebrities',
'fashion' => 'Fashion',
'beauty' => 'Beauty',
'advertising' => 'Advertising',
'bio' => 'Bio'
];
** To be clear, I know one is conditional and the other isn't. What I'm wanting to know is if the output style of the first example is equivalent to that of the second, where the key is the index of the array rather than a number being the index, and the value is still the value.
Yes, if all conditions evaluate as true, then the array format is exactly the same. Both will be associative arrays with the same key
i'm attempting to access an item in a variable being passed to me from a black box. When I use something like
var_dump($var)
to examine the contents of the variable I am given something that looks like this
array(2) {
'home' => array(6) {
'label'=> string(4) "home"
'title'=> string(15) "go to home page"
'link' => string(45) "....com/store/"
'first => bool(true)
'last' => null
'readonly' => null
}
'category2336' => array(6) {
'label' => string(9) "the title"
'link' => string(0) ""
'title' => null
'first' => null
'last' => bool(true)
'readonly' => null
}
}
How do I access the second key in this array (map)? Specifically the area labeled category2336.
If just want the key, then you can use array_keys to get an array of keys.
$keys = array_keys($var);
echo $keys[1]; // category2336