Dynamic creation of a multidimensional array in php - php

I am fetching for some values from the database, and i need to dynamicaly create a multidimensional array to look like this:
$found_data =
array(
array('2011-11-02' => 'Mobile'),
array('2011-11-02' => 'Mobile'),
array('2011-11-04' => 'Mobile'),
array('2011-11-08' => 'Desktop'),
array('2011-11-08' => 'Mobile'),
array('2011-11-08' => 'Mobile'),
array('2011-11-08' => 'Mobile'),
array('2011-11-15' => 'Mobile'),
array('2011-11-18' => 'Mobile'),
array('2011-11-21' => 'Desktop'),
array('2011-11-23' => 'Mobile'),
array('2011-11-28' => 'Desktop'),
array('2011-11-30' => 'Mobile')
);
I am thinking something in the lines of:
$found_data = array();
while($last_30_days_fetch = mysql_fetch_assoc($last_30_days_result))
{
$hit_date = $last_30_days_fetch['hit_date'];
$hit_device = $last_30_days_fetch['hit_device'];
array_push($found_data, array($clean_date=>$hit_device));
}
However the above code, does not work as intended. Any ideas?
// Thanks

You are using a variable $clean_date that is not defined. Check your error_reporting level it should report this (undefined variable).
PHP allows the use of the [] syntax to append elements to an array.
$found_data = array();
while($last_30_days_fetch = mysql_fetch_assoc($last_30_days_result))
{
$found_data[] = array(
$last_30_days_fetch['hit_date'] => $last_30_days_fetch['hit_device']
);
}

$found_data = array();
while($last_30_days_fetch = mysql_fetch_assoc($last_30_days_result))
{
$found_data[] = array($last_30_days_fetch['hit_date']=>$last_30_days_fetch['hit_device']);
}
why over complicate it or as Dan says put it into a single array there's no need for a multi array unless there's additional data you're not telling us about

Could you not just use:
$array[$hit_date] = $hit_device

Related

Use Dynamic Array inside Array PHP

I am new in PHP. I am working for send data using PHP API. Its method is like below
$createContact->setCustomFieldValues(
[
array(
'customFieldId' => 'pcVFD6',
'value' => array('35')
),
array(
'customFieldId' => 'pcVnzW',
'value' => array('37')
)
]
);
I have data in array like this
$aa = array("pcVFD6"=>"35", "pcVnzW"=>"37");
I want pass this values to above function but I am not getting idea about proper way to do it.
I have tried something like this
foreach ($aa as $key => $value){
$createContact->setCustomFieldValues([
array(
'customFieldId' => $key,
'value' => array($value)
)
]
);
}
its working but passing only last one array to API. Anyone here can please help me for achieve my goal?
Thanks!
You need to transform the array before you pass it to setCustomFieldValues. You don't want to be calling setCustomFieldValues multiple times as your current attempt does, as that's not equivalent to the original. You just need to change the structure of the array ahead of time.
For example:
$aa = array("pcVFD6"=>"35", "pcVnzW"=>"37");
$transformedArr = array();
foreach ($aa as $key => $value){
$transformedArr[] = array(
'customFieldId' => $key,
'value' => array($value)
);
}
$createContact->setCustomFieldValues($transformedArr);

Returning array of nameservers for domain php

I want to return the nameservers of a domain in php, however I'm only getting one nameserver put in the array.
This is the code I am using:
//get auth ns datat
$authnsData = dns_get_record($domain, DNS_NS);
//put the results into a nice array
foreach ($authnsData as $nsinfo)
{
$authns = array(
'nsdata' => array(
'nameserver' => $nsinfo['target'],
'ip' => $this->getnsIP($nsinfo['target']),
'location' => $this->getipLocation($this->getnsIP($nsinfo['target'])),
),
);
return $authns;
}
The result I'm getting is:
Array
(
[nsdata] => Array
(
[nameserver] => ns-us.1and1-dns.org
[ip] => 217.160.83.2
[location] =>
)
)
Lets say a domain has 2 or more nameservers, I'm only getting one of those added to the array.
If you would like to test it out to find out the issue, the code is in this file: https://github.com/Whoisdoma/core/blob/master/src/Whoisdoma/Controllers/DNSWhoisController.php#L38
The function is getAuthNS, and LookupAuthNS. Before anyone suggests using a for loop, I have tried a for ($num = 0;) type loop.
You're returning too early, so that your loop only ever runs a single iteration.
You're assigning a new array to $authns in every iteration, instead of pushing into it.
Try this piece of code instead:
foreach ($authnsData as $nsinfo)
{
$authns[] = [
'nsdata' => [
'nameserver' => $nsinfo['target'],
'ip' => $this->getnsIP($nsinfo['target']),
'location' => $this->getipLocation($this->getnsIP($nsinfo['target'])),
],
];
}
return $authns;
BTW, there's no need to run getnsIP twice. You can use this instead:
foreach ($authnsData as $nsinfo)
{
$nameserver = $nsinfo['target'];
$ip = $this->getnsIP($nameserver);
$location = $this->getipLocation($ip);
$authns[] = ['nsdata' => compact('nameserver', 'ip', 'location')];
}
return $authns;

How to auto-generate array key values if they are null (from a query)

My application uses many arrays, and many sql queries. My issue is within this code:
I execute this query:
$select = "SELECT name, surname FROM table"
$query = $connection->query($select);
$array = $query->fetchAll(PDO::FETCH_ASSOC);
Then, I pass the values into an array like this:
$array_dump= array(
array(
array('name' => 'name'),
array('content' => $array['name'])
),
array(
array('name' => 'surname'),
array('content' => $array['surname'])
),
)
In fact, this works properly, if you don't set error_reporting(). If I turn on, I get this error:
Notice: Undefined index: surname in C:\AppServ\www\test.php on line 27
This actually happens, due the array was not set. In other words, surname value is empty.
My trouble:
I must use this methodology, but I can't use something like this (got error):
array(
array('name' => 'name'),
array('content' => (isset($array['surname']) ? $array['surname'] : '')
)
My question
As you see, this ain't an error properly, but that "Notice" should not appear (as INDEX is not defined...). Is there any way to set ALL array keys by default, from that query, even if the values are NULL, such as "surname" field? That would be the fastest solution. I've been looking for this, but got no answer.
Thanks!
You should be iterating over the results and formatting them as necessary. Something like this:
$array = $query->fetchAll(PDO::FETCH_ASSOC);
$array_dump = array();
foreach ( $array as $person ) {
$tempArray = array();
array_push($tempArray, array(
'name' => 'name',
'content' => $person['name']
));
array_push($tempArray, array(
'name' => 'surname',
'content' => $person['surname']
));
array_push($array_dump, $tempArray);
}
There is no way to set ALL possible array keys by default. But you can build array of default values based on predefined set of keys and merge it with main array. Somehow like this:
$a_keys = array('name', 'surname');
$a_defaults = array_combine($a_keys, array_fill(0, count($a_keys), 0));
$array = array_merge($a_defaults, $array);
...

Use foreach in an array

im currently trying to generate a dynamic subnavigation. Therefor i pull data off of the database and store some of it an an array. Now i want to do an foreach in this array. Well as far as I know, this isn't possible.
But maybe I'm wrong. I would like to know if it would be possible, and if so how do i do it?
This is my code, which wont work since it hands out an syntax error.
$this->subnav = array(
'' => array(
'Test Link' => 'login.php',
'Badged Link' => array('warning',10023,'check.php')
),
'benutzer' => array(
'Benutzer suchen' => '/mother/index.php?page=benutzer&subpage=serach_user',
'Benutzer hinzufügen' => '/mother/index.php?page=benutzer&subpage=add_user',
'Rechtevergabe' => '/mother/index.php?page=benutzer&subpage=user_rights'
),
'logout' => array(
'Login' => '/mother/login.php',
'Logout' => '/mother/index.php?page=logout'
),
'datenbank' => array(
(foreach($this->system->get_databases() as $db){array($db->name => $db->url)}),
'Deutschland' => '/mother/login.php',
'Polen' => '/mother/index.php',
'Spanien' => '/mother/index.php',
'Datenbank hinzufügen' => '/mother/index.php?page=datenbank&subpage=add_database'
)
);
}
You can't place foreach loop inside an array like this. You can do something like this though.
foreach($this->system->get_databases() as $db)
{
$this->subnav['datenbank'][$db->name] = $db->url;
}
This is not possible. but you can do it in other way like you can place the foreach outsite and top of this array and assign to an array and then you can use that array variable.
e.g.
$arrDB = array();
foreach($this->system->get_databases() as $db) {
$arrDB[$db->name] = $db->url;
}
Now assign it to:
'datenbank' => $arrDB

An array of MySQL results...

What am I doing wrong here?
I am attempting to return a json object and I can't seem to get past the array... I've built hundreds of regular array and returned them as a json object but I am having a hard time wrapping my head around this one.
$rows = array();
$post_array = array();
$i = 0;
$result = mysql_query(" SELECT * FROM forum_posts WHERE permalink = '$permalink' AND LOWER(raw_text) LIKE '%$str%' " );
while($row = mysql_fetch_assoc($result))
{
$post_array[$i] = $rows[ "id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate ];
$i++;
}
It looks like you mean to define an array for $post_array[$i] = .... Like this?
$post_array[$i] = array(
"id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate,
);
(Also, I just took the liberty to respace that a little for readability.)
To convert your array to JSON, pass it to json_encode().
Update: Oh, before you ask about it, I just noticed I added a comma out of habit after the last item in the array. It looks like it's out of place, but it's actually fine to have it there when defining arrays. It doesn't serve any special purpose, but it allows you to copy/paste/remove lines from the array without having to worry about whether or not to add/remove a trailing comma.
As an aside, you don't have to manually increment a numeric array index $i. If you just do this:
$post_array[] = array(...);
it will automatically assign the next available numeric index.
Do you mean do be doing something like this:
$post_array = array();
$i = 0;
$result = mysql_query(" SELECT * FROM forum_posts WHERE permalink = '$permalink' AND LOWER(raw_text) LIKE '%$str%' " );
while($row = mysql_fetch_assoc($result))
{
$post_array[$i] =array( "id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate );
$i++;
}
Then you can simply use json_encode to encode your array as json.
e.g.
echo json_encode($post_array);
You can't build an array the way you were with $rows[...], you need to use array. Also, instead of managing the ordinals for your array, you can just use array_push

Categories