Before anything, I'll show you my table:
(In the context of PHP)
I'd like to create a multidimensional array via a query - So that a group of tags with the same id will end up in the same place:
<?php
// Given the above example table, it would essentially produce this:
$my_1 = array
( array('ect'),
array('123', 'tag'),
array('lolly', 'hat')
);
Is that a possibility? I've achieved the same result by looping through queries, but it's terribly inefficient.
<?php
$array = array();
foreach($tags as $tag)
{
if(array_key_exist($tag->id,$array)){
//if key is assigned in array, we can push value to key
$array[$tag->id] = array_push($tag->value,$array[$tag->id]);
}else{
//if key is not assigned we will create key and push value
$array[$tag->id] = $tag->value;
}
}
//usage
print_r($array[7]); // list tags with id 7
?>
Use a 2-dimensional array:
$array = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$tag = $row['tag'];
if (isset($array[$id])) {
$array[$id][] = $tag;
} else {
$array[$id] = array($tag);
}
}
The resulting $array will be
array(1 => array('ect'),
7 => array('123', 'tag'),
9 => array('lolly', 'hat'))
Related
Here's my Query
$rows = $mydb->get_results("SELECT title, description
FROM site_info
WHERE site_id='$id';");
I get something like:
Title1 Desc1
Title2 Desc2
etc.
I want to put that data in array so I do:
$data = array();
foreach ($rows as $obj) {
$data['title'] = $obj->title;
$data['description'] = $obj->description;
}
When I do:
print_r($data);
I only get title and description of first item... Please help :/ I checked and my query returns all what i want to be in array not only the first row.
You are over-writing array indexes each time in iteration.You need to create new indexes each time when you are assigning the values to array.
So either do:-
$data = array();
foreach ($rows as $key=>$obj) { // either use coming rows index
$data[$key]['title'] = $obj->title;
$data[$key]['description'] = $obj->description;
}
Or
$data = array();
$i=0; //create your own counter for indexing
foreach ($rows as $key=>$obj) {
$data[$i]['title'] = $obj->title;
$data[$i]['description'] = $obj->description;
$i++;// increase the counter each time after assignment to create new index
}
For display again use foreach()
foreach ($data as $dat) {
echo $dat['title'];
echo $dat['description'];
}
If the eventual goal is simply to display these values, then you shouldn't bother with re-storing the data as a new multi-dimensional array.
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id='$id';");
If $id is user-supplied data or from an otherwise untrusted source, you should implement some form of sanitizing/checking as a matter of security. At a minimum, if the $id is expected to be an integer, cast it as an integer (an integer doesn't need to be quote-wrapped).
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id = " . (int)$id);
When you want to display the object-type data, just loop through $rows and using -> syntax to echo the values.
echo "<ul>";
foreach ($rows as $obj) {
echo '<li>' , $obj->title , ' & ' , $obj->description , '</li>';
}
}
echo "</ul>";
If you have a compelling reason to keep a redundant / restructured copy of the resultset, then you can more simply command php to generate indexes for you.
foreach ($rows as $obj) {
$data[] = ['title' => $obj->title, 'id' => $obj->id];
}
The [] is just like calling array_push(). PHP will automatically assign numeric keys while pushing the associative array as a new subarray of $data.
I have php result set, and from these result i am extracting value using php foreach loop. I put the foreach loop value in array $summery[]. but when i try to print value its print value at once. but i need separate value/result set for each foreach loop as json code so that i can print each result separately. My foreach loop following :
foreach($result_UserWrSet as $UserWrInfo) {
$summery[]=$UserWrInfo['wr_id'];
$summery[]=$UserWrInfo['wr_number'];
$summery[]=$UserWrInfo['wr_title'];
$dateFlag=1;
$result_StartDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$result_EndDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$summery[]=$result_StartDate;
$sql_GetUserName = "SELECT user_name FROM user_information where user_id='$UserWrInfo[user_id]'";
$result_GetUserName = mysqli_query($conn, $sql_GetUserName);
$num_GetUserName = mysqli_num_rows($result_GetUserName);
if ($num_GetUserName > 0){
$UserNameByIdRos = $result_GetUserName->fetch_assoc();
$UserNameById=$UserNameByIdRos['user_name'];
}
else {$UserNameById=NULL;}
$summery[]=$UserNameById;
$result_CurrentHop = $WrDates ->getCurrentHopByWrId($UserWrInfo['wr_id']);
$result_CurrentHopName = $WrDates ->GetHopsNameById($result_CurrentHop);
$summery[]=$result_CurrentHopName;
$result_EndDate = $WrDates ->completedDate($UserWrInfo['wr_id']);
$summery[]=$result_EndDate;
}
print json_encode($summery);
My result become
["69","010116-69","Wr test","01\/01\/16 18:45 PM","planner","Done","01\/01\/16 19:16 PM","68","010116-","This is title","01\/01\/16 18:44 PM","planner","Done"]
but i need :
[["69","010116-69","Wr test","01\/01\/16 18:45 PM","planner","Done"],["01\/01\/16 19:16 PM","68","010116-","This is title","01\/01\/16 18:44 PM","planner","Done"]]
Use this code, you need to use another array in which all the sub array's to be pushed and encode that array after pushing all the items into it
<?php
$dataArray = array(); /// empty array in which sub array's to be pushed..
foreach($result_UserWrSet as $UserWrInfo) {
$summery= array();
$summery[]=$UserWrInfo['wr_id'];
$summery[]=$UserWrInfo['wr_number'];
$summery[]=$UserWrInfo['wr_title'];
$dateFlag=1;
$result_StartDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$result_EndDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$summery[]=$result_StartDate;
$sql_GetUserName = "SELECT user_name FROM user_information where user_id='$UserWrInfo[user_id]'";
$result_GetUserName = mysqli_query($conn, $sql_GetUserName);
$num_GetUserName = mysqli_num_rows($result_GetUserName);
if ($num_GetUserName > 0){
$UserNameByIdRos = $result_GetUserName->fetch_assoc();
$UserNameById=$UserNameByIdRos['user_name'];
}
else {$UserNameById=NULL;}
$summery[]=$UserNameById;
$result_CurrentHop = $WrDates ->getCurrentHopByWrId($UserWrInfo['wr_id']);
$result_CurrentHopName = $WrDates ->GetHopsNameById($result_CurrentHop);
$summery[]=$result_CurrentHopName;
$result_EndDate = $WrDates ->completedDate($UserWrInfo['wr_id']);
$summery[]=$result_EndDate;
////Push sub array i.e summary into the main array...
$dataArray[] = $summery;
}
print json_encode($dataArray);
?>
You need a multidimensional array, you can follow below code:
$result_UserWrSet = array(
'0' => array('wr_id'=>'12','wr_number' =>'785', 'wr_title' => 'title1'),
'1' => array('wr_id'=>'12','wr_number' =>'785', 'wr_title' => 'title1'));
foreach($result_UserWrSet as $key => $UserWrInfo) {
$summery[$key][]=$UserWrInfo['wr_id'];
$summery[$key][]=$UserWrInfo['wr_number'];
$summery[$key][]=$UserWrInfo['wr_title'];
}
print json_encode($summery);
output: [["12","785","title1"],["12","785","title1"]]
Good Luck :)
Currently, you are just adding new items to a one dimensional array. You need to create a separate array per result, like this:
foreach($result_UserWrSet as $UserWrInfo) {
$item = array();
// Change all $summary in the loop to: $item, like this:
$item[]=$UserWrInfo['wr_id'];
$item[]=$UserWrInfo['wr_number'];
$item[]=$UserWrInfo['wr_title'];
//...and so on
// Then add this last in your loop:
$summary[] = $item;
}
This will create one array per iteration that is put in the main array, which then becomes a multi dimensional array.
I am needing to add data dynamically into a multidimensional array. The data comes from a query in the database. I can see through the "echo" all elements, but in time to add to the multidimensional vector data and overwrite only the last record is added.
My example below:
$queryu = "SELECT * FROM usuario ORDER BY id";
$stmtu = $con->prepare($queryu);
$stmtu->execute();
$numu = $stmtu->rowCount();
$j = 0;
$lista;
if ($numu > 0) {
$colunas = 3;
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
extract($rowu);
$lista['id'] = $id;
$lista['nome'] = $nome;
$j++;
}
}
The result:
id - 6
nome - teste
This is the last record added.
Thanks!!!
You don't create a multi dimensional array by now. You just update create two key => value pairs id and nome. If you want to store multiple of them you have to create a multidimensional array which means an array inside another array:
$lista = array(); // init your array!
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
extract($rowu);
$lista[] = array(
'id' => $id,
'nome' => $nome
);
$j++;
}
Or do it even smarter (if the keys in the final array are the same as the column names):
$lista = array(); // init your array!
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
$lista[] = $rowu;
$j++;
}
Modify your code as follows
$queryu = "SELECT * FROM usuario ORDER BY id";
$stmtu = $con->prepare($queryu);
$stmtu->execute();
$numu = $stmtu->rowCount();
$lista = array();
if ($numu > 0) {
$colunas = 3;
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
extract($rowu);
$lista[] = array('id' => $id, 'nome' => $nome);
}
}
As you probably noticed here, I've removed j index (you don't need it; I suppose that you would use it as "first-level-index" of your multidimensional array) and added that statement: $lista[] =. "Magic" happens just there: with this command ($arrayname[] =) you can append to existent array a new element.
However I don't know from where you're obtaining $id and $nome so this snippet could fail due to undefined variables and similar
I have a custom PHP function which executes a stored procedure and returns an array:
function test(){
$in = array("abc","bcd","efg");
$result = mydba->executestoredprocedure('proc1',$in);
$arr_sim = array();
foreach ($result['recordset'] as $rows) {
if (!empty($rows)) {
echo $arr_sim[$rows['field1']] = $rows['field2'];
}
}
return $arr_sim;
}
In the above function $arr_sim is returning the number of items correctly when the rows["field1"] values are different. If the rows["field1"] values are the same then it is overwriting the first value and returning only the last one. How can I overcome this?
array ( [chicago] => 'sears', [rochester] => 'liberty' )
If the $arr_sim contains these items then it is returned correctly. Because the keys are different.
array ( [chicago] => 'MCD', [chicago] => 'TACOBELL' )
If the $arr_sim contains these items then it is not returned correctly. Because the keys are the same, "chicago".
Array keys must be unique. Instead, do something like this:
// You want the array to look like this
// array('chicago' => array('MCD', 'TACOBELL'));
function test(){
$in = array("abc","bcd","efg");
$result = mydba->executestoredprocedure('proc1',$in);
$arr_sim=array();
foreach ($result['recordset'] as $rows) {
if(!empty($rows)){
if(array_key_exists($rows['field1'], $arr_sim) {
$arr_sim[$rows['field1']][] = $rows['field2'];
} else {
$arr_sim[$rows['field1']] = array($rows['field2']);
}
}
}
return $arr_sim;
}
Replace $arr_sim[$rows['field1']] = $rows['field2'] with $arr_sim[$rows['field1']][] = $rows['field2']. This will create an array of arrays.
echo $arr_sim['chicago'][0]; // MCD
echo $arr_sim['chicago'][1]; // TACOBELL
Technically, you should write something like this to avoid notices:
if (!isset($arr_sim[$rows['field1']])) $arr_sim[$rows['field1']] = array();
$arr_sim[$rows['field1']][] = $rows['field2'];
But you must really ask yourself, is the field1 (city names) worthy of being the primary key for the array? If not, you should choose some other identifier.
How can I add key value pairs to an array?
This won't work:
public function getCategorieenAsArray(){
$catList = array();
$query = "SELECT DISTINCT datasource_id, title FROM table";
if ($rs=C_DB::fetchRecordset($query)) {
while ($row=C_DB::fetchRow($rs)) {
if(!empty($row["title"])){
array_push($catList, $row["datasource_id"] ."=>". $row["title"] );
}
}
}
return($catList);
}
Because it gives me:
Array ( [0] => 1=>Categorie 1 [1] => 5=>Categorie 2 [2] => 2=>Caterorie 2 )
And I expect:
Array ( [1] =>Categorie 1 [5] => Categorie 2 )
$data =array();
$data['user_code'] = 'JOY' ;
$data['user_name'] = 'JOY' ;
$data['user_email'] = 'joy#cargomar.org';
Use the square bracket syntax:
if (!empty($row["title"])) {
$catList[$row["datasource_id"]] = $row["title"];
}
$row["datasource_id"] is the key for where the value of $row["title"] is stored in.
My PHP is a little rusty, but I believe you're looking for indexed assignment. Simply use:
$catList[$row["datasource_id"]] = $row["title"];
In PHP arrays are actually maps, where the keys can be either integers or strings. Check out PHP: Arrays - Manual for more information.
You can create the single value array key-value as
$new_row = array($row["datasource_id"]=>$row["title"]);
inside while loop, and then use array_merge function in loop to combine the each new $new_row array.
You can use this function in your application to add keys to indexed array.
public static function convertIndexedArrayToAssociative($indexedArr, $keys)
{
$resArr = array();
foreach ($indexedArr as $item)
{
$tmpArr = array();
foreach ($item as $key=>$value)
{
$tmpArr[$keys[$key]] = $value;
}
$resArr[] = $tmpArr;
}
return $resArr;
}
No need array_push function.if you want to add multiple item it works fine. simply try this and it worked for me
class line_details {
var $commission_one=array();
foreach($_SESSION['commission'] as $key=>$data){
$row= explode('-', $key);
$this->commission_one[$row['0']]= $row['1'];
}
}