I am stumbling on something annoying and hope you can shed some light. I am generating an array via PHP MySQL query. My WHILE statement is as follows:
$model[constraints][d][] = array($row['Node'] => array("max" => $row['dem'], "min"=> $row['dem']));
The problem is that each new array added to $model[constraints][d] gets enclosed by an array. See screenshot below:
I don't want there to be array "0" around Norway. I would like to be able to access my values as follows:
$model[constraints][s][Norway][max]
Right now, the only way I can access that value is by doing the following:
$model[constraints][s][0][Norway][max]
How should I amend my while statement to get the desired array? Thank you for your time.
Before the loop you could do:
$model[constraints][d] = array();
And then just change the statement inside the loop to:
$model[constraints][d] += array($row['Node'] => array("max" => $row['dem'], "min"=> $row['dem']));
Here's a live demo
Related
I have an array named 'users' in which I am storing some variables as you see below.I want to verify if the 'nume' (name) value already existing in this array is the same as the value introduced by a person in a search box. I've tried some methods but I haven't obtained the wanted result. I think it is something obvious I can't see at the moment.
EDIT : The image is the result of var_dump() of my code. I am using it for people to understand what I want to know.
it's simple, try that:
$searchValue = 'victor';
$index = array_search($searchValue, array_column($users, 'nume'));
I am trying to build an associative array to save the following information. A url, a word, and a frequency (# of occurrences of that word on that webpage).
I want to be able to access the information where I enter a string for the url and word and receive the frequency, like this:
$test["somewhere.com"]["biology"] => 5
$test["somewhere.com"]["auto"] => 10
$test["elsewhere.com"]["biology"] => 7
Right now I am pulling the information out of a db one row at a time and am trying the following:
$test["$url"] = array("$word" => "$freq");
After every iteration it gets over written. How do I change the syntax to avoid this situation? Is it possible to build the structure I want?
Thanks.
EDIT:
I was assigning values to array in a while loop. I made the mistake of initializing the array within the loop. I wasn't overwriting entries, I was
re-initializing the array unintentionally. That was my problem.
You are reassigning $test["$url"] as a new array each time. Use the full path:
$test[$url][$word] = $freq;
Also, no need for the quotes.
Instead of overwriting the first level contents, declare a new property for it. (without knowing how are you getting your urls, words and frequencies, the following is just an example)
$test = []
foreach($urls as $url => $words) {
$test[$url]=[];
foreach( $words as $word => $freq) {
$test[$url][$word] = $freq;
}
}
However, this looks awfully like trying to build an associative array that's already built.
I am trying to merge a static data with json encode array data for output. Here is my php code:
$arr = array();
$rs = mysql_query("SELECT id, name, picture, mail, gender, birthday FROM users WHERE id='$logged_id' ");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":'.json_encode($arr).'}';
Now I want to merge other data with it:
$user_ip = array("user_ip" => $user_ip_address);
I have tried array_merge($arr, $user_ip). But it didn't work. I think this is not correct json array format if I merge with existing data array. Please let me know what to do how to output other data as well as current data coming from mysql with json encode.
I am getting such output with my existing code, which is correct:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11"}]}
But now I want to add other variable e.g $user_ip_address as user's data joining with current output data like this:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11",user_ip:"127.0.0.1"}]}.
I want to get it in this way. How to do it? Please let me know. Thanks in advance.
try this:
echo json_encode(array('users' => $arr, 'user_ip' => $user_ip_address));
on a side note:
you should use PHP PDO class to connect and query the database.
mysql_fetch_object returns an object, not an array. So, what are you doing by $arr[] = $obj; is just adding an object into an array. So, the actual structure of the $arr is something like
$arr => [
[0] => Object(....),
[1] => Object(....),
....
]
In your particular case, I assume you are fetching single row by primary key, so there are only one object.
THe simpliest way to fix this is to add a field to an object. I haven't worked with PHP since 5.3, so can't be sure, but it's as simple as adding
$obj->user_ip = $user_ip_address;
inside the loop.
Btw, a couple of questions for you:
Why do you use loop if it should result in a single row?
Why you are embedding the variable directly into SQL query. It's quite vulnerable, read about sql-injections and how to prevent it (one day I was really tired telling people here on SO to use PDO and prepared statements, so just go read about it),
Have you read the documentation about mysql_fetch_object and array_merge? Why not (because if you have read it you wouldn't be asking the question).
Tried debugging? E.g. attaching a debugger and watching for variables contents? Inserting logging or (God forgive me) debug print with echo?
"Didn't work" is a quite bad error description. This time you was lucky, because the error was obvious. Next time, please, be more specific.
Given this in the Smarty template:
<pre>{$user->settings['sendStats']|#print_r:1}</pre>
The output in the browser is this:
Array
(
['period'] => daily
['ofPeriod'] => year
['points'] => 1000
)
Doing any of these:
<pre>{$user->settings['sendStats']['period']|#print_r:1}</pre>
<pre>{$user->settings['sendStats'][ofPeriod]|#print_r:1}</pre>
<pre>{$user->settings['sendStats'].points|#print_r:1}</pre>
<pre>{$user->settings.{'sendStats'}.{'period'}|#print_r:1}</pre>
<pre>{$user->settings.{sendStats}.{period}|#print_r:1}</pre>
with or without the |#print_r:1 gives no output in the browser.
I also tried assigning $user->settings to a Smarty variable and I get the exact same result (as expected).
How do I access the elements of the $user->settings['sendStats'] array?
{$user->settings.sendStats.period|#print_r:1} should work just fine. Also have a look at the Variables page in the docs…
The array values itself are not arrays (your array is not multidimensional), so you should drop the |#print_r:1 and you should be fine. Should look something like:
<pre>{$user->settings['sendStats']['period']}</pre>
Finally figured it out. The array keys contained single quotes, so the answer would have been:
{$user->settings['sendStats']["'period'"]}
I fixed it so the keys didn't contain quotes anymore.
I'm new to programming and I'm tackling arrays. I thought I had multi-dimensional arrays figured out but I guess I don't. Here's the code I'm working on:
$loopcounter = 0;
while ($myrow = mysql_fetch_array($results)) {
//...other stuff happens...
$allminmax[$loopcounter][] = array("$myrow[3]","$currentcoltype","$tempmin","$tempmax");
$loopcounter++;
}
This chunk of code is supposed to create an array of four values ($myrow[3], currentcoltype, tempmin, tempmax) and insert it into another array every time the loop goes through. When I do this:
echo implode($allminmax);
I get:
ArrayArrayArrayArrayArrayArrayArrayArrayArray
Do I need to implode each array before it goes into the master array? I really want to be able to do something like $allminmax[0][4] and get the $tempmax for the first row. When I try this now nothing happens. Thanks -- any help is appreciated!
It looks like you should either use [$loopcounter] or [], but not both. You also should drop the quotes. They're unnecessary and in the case of "$myrow[3]" they interfere with the variable interpolation.
$allminmax[] = array($myrow[3], $currentcoltype, $tempmin, $tempmax);
By the way, arrays are zero-indexed, so to get $tempmax for the first row it'd be $allminmax[0][3] not $allminmax[0][4].
Also, a better way to display the contents of your array is with print_r or var_dump. These will display arrays within arrays while a simple echo will not.
var_dump($allminmax);