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
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.
How to sort the following array?
I have an multidimensional array that gets filled with total hours for each brand
$totalHours = array(
'brand' => array(),
'project' => array(),
'hours' => array()
);
The output is something like this (project is not filled):
array(3) {
["brand"]=>
array(3) {
[0]=>
string(4) "Nike"
[1]=>
string(9) "Coke Cola"
[2]=>
string(8) "Converse"
}
["project"]=>
array(3) {
[0]=>
string(6) "Bonobo"
[1]=>
string(4) "LDRU"
[2]=>
string(2) "US"
}
["hours"]=>
array(3) {
[0]=>
int(28)
[1]=>
int(106)
[2]=>
string(1) "2"
}
}
Now I would like to sort the array based on the "hours" field.
I've tried the array_multisort but it seems like I simply don't get how this function works and how to apply it to this array.
I have been able to sort an single array with just one row of values. If I apply that to this problem im sorting only the hours field, leaving the others unsorted and therefore the array is corrupted.
The "project" does actually contains a string. It always does. In this example I didn't filled it.
array_multisort should work:
$totalHours = array(
'brand' => array('Nike', 'Coke Cola', 'Converse'),
'project' => array(),
'hours' => array(28, 106, '2')
);
array_multisort($totalHours['hours'], $totalHours['brand']);
var_dump($totalHours);
That data format is not very convenient because there is no direct association between brands and hours, they even sit in different arrays! Plus, the last hour is a string, not an integer.
We're going to have to create an intermediate array to associate them and sort them. We'll then re-inject everything in the original array.
// Make sure both arrays of brands and hours and the same size
if (count($totalHours['brand']) != count($totalHours['hours'])) {
throw new Exception('Invalid data!');
}
// Make sure every hour record is an integer, not a string
$totalHours['hours'] = array_map('intval', $totalHours['hours']);
// array_combine will sort all arrays based on the sorting of the first one
array_multisort($totalHours['hours'], $totalHours['brand'], $totalHours['project']);
EDIT: Using array_multisort was #delprks 's idea originally. Here I applied it to both brand and project arrays.
You cant do that with a single array_* function!
if (project is not filled) always and the indexes of brand and hours are equal, then you can do:
$forsort = array_combine($totalHours["brands"],$totalHours["hours"]);
asort($forsort,SORT_NUMERIC);
$totalHours["brands"]=array_keys($forsort);
$totalHours["hours"]=array_values($forsort);
But, this is just an answer for you question, not best practise at all.
I have an array of database objects and I'm using foreach() to present the names and projects. Good, now the customer doesn't want duplicate names for when one person has multiple projects. This has to do with variable scope and this is my failed attempt to pull this stunt off. Here's a partial var_dump of the array of objects.
array [
0 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "Bone density scanner analysis"
}
1 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "analysis of foot"
}
]
What I want to end up with is:
array [
0 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "Bone density scanner analysis"
}
1 => {
["lastName"]=>
string(1) ""
["projectName"]=>
string(16) "analysis of foot"
}
]
Here's what I was thinking that doesn't seem to work:
function suppress_name($name){
global $string;
return ($name == $string) ? '' : $string;
}
function overall() {
//$result = database call to get objects
foreach ($result as $item) {
$string = $item->lastName;
$rows = array('Name' => suppress_name($item->lastName), 'project' => $item->projectName);
}
}
Researching I see several references to array_unique() which I use for a flattened array, but I can't see that it would help me here. OK, I thought I could make a function, like the above, to handle duplicates and use the $global but think I'm not grasping how to use globals in this instance. I'm happy to be pointed to a better way, or better search terms. Does this make sense?
Here is a possible approach to your solution, where we store the last names in a one dimensional array then check against it through each iteration of the array. If the lastName is in the array then set the value to ''.
Note the use of the reference (&).
<?php
$arrays = array(
array('lastName' => 'w', 'projectName' => 'Bone density scanner analysis'),
array('lastName' => 'w', 'projectName' => 'analysis of foot')
);
$last_names = array();
foreach($arrays as &$array){
if( in_array($array['lastName'],$last_names) ){
$array['lastName'] = '';
}else{
$last_names[] = $array['lastName'];
}
}
echo '<pre>',print_r($arrays),'</pre>';
It would be easier to work with nested arrays
array [
0 => {
["lastName"]=> string(1) "w"
["projects"]=> array [
0 => {
["projectName"] => string(29) "Bone density scanner analysis"
}
1 => {
["projectName"]=> string(16) "analysis of foot"
}
1 => {
["lastName"] => string(1) "x"
["projects"] => array [
0 => {
["projectName"] => string(16) "analysis of head"
} ]
}
]
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));
array(24) { ["user_id"]=> string(1) "9" ["facebook_id"]=> string(15) "381305418721463" ["first_name"]=> string(4) "John" ["last_name"]=> string(4) "Does" ["current_latitude"]=> string(10) "-37.825697" ["current_longitude"]=> string(10) "144.999965" ["current_address"]=> string(45) "229 Swan Street, Richmond VIC 3121, Australia" ["date_of_birth"]=> string(10) "01/01/1990" ["city"]=> string(30) "Melbourne, Victoria, Australia" ["country"]=> string(0) "" ["email_address"]=> string(22) "bzingatester#gmail.com" ["profile_pic"]=> string(0) "" ["first_login"]=> string(2) "no" ["blocked_users_id"]=> string(0) "" ["my_friend"]=> string(52) "10152805813948795,10155307822515151,1389504958030240" ["search_radius"]=> string(2) "50" ["device_type"]=> string(3) "ios" ["device_id"]=> string(1) "1" ["device_token"]=> string(64) "6ddaf9d59418e99b1c9cb28c21d94647bfed9f78a80b410164c1f2798beee84a" ["hideFromActivityFeed"]=> string(2) "no" ["hideFromFriendsofFriends"]=> string(2) "no" ["hideNotification"]=> string(2) "no" ["created_date"]=> string(19) "2015-01-07 01:00:11" ["modified_date"]=> string(19) "2015-02-27 05:36:12" }
In PHP I have an array called $userData as per above, I want to be able to echo values such as first name 'first_name', using code like this
echo $userInfo->first_name;
(this doesnt seem to work)
I DO NOT want to loop and fetch all keys in array using foreach, just get values 'first_name', 'last_name' ect. from the array
Please try like this,
$first_name = $userInfo['first_name'] // $userInfo is array name
You can change the array to object and then use -> like below
$userData= (object) $userData;
And then
$userData->firstName ..etc
Please use type casting.
$userinfo = (array)$userInfo;
Then you access your key first_name.
echo $userinfo['first_name'];
First of use a different method to dump data ..
echo "<pre>";
print_r($your_array);
exit;
It just simply bodes for a better presentation to see what is an object and what is an array.
You cannot access array members with the object notation. You can however cast your array as an object.
(object)$yourarray;
If you want to access array members, use :
$yourarray['first_name'];
If you cast as an object:
$obj = (object)$yourarray;
Now access:
$obj->firstname;
Hope that helps.
Actually we use arrays in programming to prevent loop or something like this to find a value, so instead of this structure,
$a = 'text1';
$b = 0;
$c = true;
$d = 'text2';
we use arrays:
$array = array('a' = > 'text1', 'b' => 0, 'c' => true, 'd' => 'text2' );
and to access the value of some key, we call the key name, inside brackets after array's name:
echo $array['a'];
//will echo text1
//or
echo $array['b'];
//will echo true
This is associative array...
if you just pass values to an array without keys, php will use numeric keys instead...
$array = array( 'text1', '0', true, 'text2' );
$array[0] = 'text1';
$array[1] = 0;
$array[2] = true;
$array[3] = 'text2';