Selecting variable and storing into multi-dimentional array - php

I understand how multi-dimentional array works but iam new to it.
eg.
$arrayAns = array( subject => "he"),
array( subject => "I"),
array( subject => "they");
What I am trying to do is, get a variable from database and store it in the array.
$query = "SELECT subject FROM #__wordBank ORDER BY RAND() LIMIT 1";
$db->setQuery($query);
$rows=$db->loadObjectList();
$arrayAns = array( subject => "$rows")
Is that the way to do it?

Try this:
If the results from database are stored in rows:
$newArray = array();
foreach($rows as $key=>$value) {
$newArray[] = $value;
}
Here, all the variables in $value would be stored into the newArray.
Also, see array_push

Almost! But not quite
Here is how I would go about this:
$arrayAns = array(
array('subject' => "he"),
array('subject' => "I"),
array('subject' => "they")
);
$query = "SELECT subject FROM #__wordBank ORDER BY RAND() LIMIT 1";
$db->setQuery($query);
$rows=$db->loadObjectList();
$arrayAns[] = array('subject' => $rows);

Depending on what DB API are you using you may have an option to retrieve the data as a multidimensional array automatically. Check if $rows->toArray() is possible or something like that.
Otherwise not the most optimal, but easy and clean way is to foreach through your $rows list and build the array you want.
Btw, the array you have defined on top is defined like this in PHP:
$myArray = array(
array(
'subject' => 'he'
),
array(
'subject' => 'I'
),
array(
'subject' => 'they'
)
);

Change you syntax to look like this (you also had some syntax errors) -
// original multidimensional array
$arrayAns = array(
array( "subject" => "he"),
array( "subject" => "I"),
array( "subject" => "they")
);
// execute query
$query = "SELECT subject FROM #__wordBank ORDER BY RAND() LIMIT 1";
$db->setQuery($query);
$rows=$db->loadObjectList();
Now what we want to do is add another element to your original array. You can use the short hand [] syntax to push another element on to the top of the array.
$arrayAns[] = array('subject'=> $rows['subject']);
That line is functionally identical to this one -
array_push($arrayAns, array('subject'=> $rows['subject']));

Related

Defining array in array in array - php

I am trying to create the following array dynamically:
$aSettings = array( "text"=>
array( "icon_type" =>
array(
"name"=>"icon_type",
"method"=>"dropdown",
"option"=>"",
"default"=>""
),
"column" =>
array(
"name"=>"column_count",
"method"=>"dropdown",
"default"=>"1"
)
)
)
I am not sure how to declare the array into the array.
I have the following example code:
$aSettings=array();
$aSetting_type['text']=array();
$aSetting_name['icon_type']=array();
$aSetting_name['column']=array();
$aSetting_values1=array('name'=>'icon_type','method'=>'dropdown','option'=>'','default'=>'');
$aSetting_values2=array('name'=>'column_count','method'=>'dropdown','default'=>1);
I guess I am overlooking something very simple, but how do I put all these arrays into each other?
I want to be able to call a value from the array as:
$aSettings['text']['column']['name'];
Any ideas?
You could do:
$aSettings['text']['icon_type'] = $aSetting_values1;
$aSettings['text']['column'] = $aSetting_values2;
If you need it more dynamic, you could use variables like so:
$type = 'text';
$name1 = 'icon_type';
$aSettings[$type][$name1] = $aSetting_values1;
Collect the array is reverse lower to higher order, it would be easy to collect without confusions, for example
$icon_type = array(
"name"=>"icon_type",
"method"=>"dropdown",
"option"=>"",
"default"=>""
);
$column = array(
"name"=>"column_count",
"method"=>"dropdown",
"default"=>"1"
);
$text = array(
"icon_type" => $icon_type,
"column" => $column
);
$aSettings = array(
"text"=> $text
);
Once you collect array like this you can easily access any element in the array i.e. echo $aSettings['text']['column']['name'];

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);
...

sql result as array of arrays

i'm trying to format the output of a sql query as an array of arrays, for using the gannti class graph tool on my sql data. I'm not very experienced(outside industrial plc's), and can't seem to find a solution to this particular problem despite lots of googeling.
The sql query i want to perform looks like this:
$query = "SELECT label, start, end from oppgaver ";
And the original array showed in the gannti class example is written like this:
$data = array();
data[] = array(
'label' => 'alarmkit',
'start' => '2013-08-01',
'end' => '2013-09-10'
);
$data[] = array(
'label' => 'Stekeovnskontroller',
'start' => '2013-08-22',
'end' => '2013-09-01'
);
$data[] = array(
'label' => 'Tull og fanteri',
'start' => '2013-09-02',
'end' => '2013-09-10'
);
And then you call the gantti to do it's thing:
$gantti = new Gantti($data, array(
'title' => 'Elektro',
'cellwidth' => 15,
'cellheight' => 35,
'today' => true
));
All works well, except for my unability to format the sql output to what i assume is an array of arrays so the gantti class can do its magic. I got it to show the first letter of each label in the sql database once, but that piece of mangled code i wrote should probably be forgotten :-)
Does anyone here have a idea about how to do this?
Update:
The last way i tried to get the data, by using msql_fetch_assoc.
Unfortunately i did not keep a record of the different approaches i made.
I've also tried several examples i found on using mysql_fetch_array, and mysql_fetch_row.
$query = "SELECT label, start, end from oppgaver ";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_assoc($result)) {
array_push($data, $row[0]);
}
Use $row to push in array in place of $row[0]
As given below
while ($row = mysql_fetch_assoc($result)) {
array_push($data, $row);
}

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

Need help about array

What do
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
mean?
Thanks a lot.
How should i format the output so i can learn the results that was returned?
You can format your code into tables by looping on the array using for or foreach. Read the docs for each if you don't have a grasp on looping.
2.What does
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
The first line assigns an associative array to another element of the $categories array. For instance if you wanted the name of the category with ID of 6 it would look like this:
$categories[6]['name']
The second line does something similar, except when you are working with an array in PHP, you can use the [] operator to automatically add another element to the array with the next available index.
What is the uses of .= ?
This is the concatenation assignment operator. The following two statements are equal:
$string1 .= $string2
$string1 = $string1 . $string2
These all have to do with nesting arrays.
first example:
$categories[$id] = array('name' => $name, 'children' => array());
$categories is an array, and you are setting the key id to contain another array, which contains name and another array. you could accomplish something similar with this:
$categories = array(
$id => array(
'name' => $name,
'children' => array()
)
)
The second one is setting the children array from the first example. when you have arrays inside of arrays, you can use multiple indexes. It is then setting an ID and Name in that array. here is a another way to look at example #2:
$categories = array(
$parentID => array(
'children' => array(
'id' = $id,
'name' => $name
)
)
)
note: my two ways of rewriting are functionally identical to what you posted, I'm just hoping this makes it easier to visualize what's going on.

Categories