Sorting Multi-diminsional array - php

i am trying to sort multi_diminsional array using array_multisort()
but it does nothing to the original array.
here is my code :
foreach ($aOrderArticles as $oOrderArticle) {
$aOrderArticleExportData[$sUserId][$sArticleId]['lastname'] = $oOrder->oxorder__oxbilllname->value;
$aOrderArticleExportData[$sUserId][$sArticleId]['firstname'] = $oOrder->oxorder__oxbillfname->value;
$aOrderArticleExportData[$sUserId][$sArticleId]['title'] = $sTitle;
$aOrderArticleExportData[$sUserId][$sArticleId]['amount'] += $oOrderArticle->oxorderarticles__oxamount->value;
}
$aSortedLastNames = array();
$aSortedFirstNames = array();
foreach($aOrderArticleExportData as $sUserId => $aUserData){
foreach($aUserData as $aArticleData){
$aSortedLastNames [] = $aArticleData ['lastname'];
$aSortedFirstNames [] = $aArticleData ['firstname'];
}
}
array_multisort($aSortedLastNames,SORT_ASC,$aSortedFirstNames,SORT_ASC,$aOrderArticleExportData);

I have fixed the problem by using one foreach loop and getting the current element.
The problem was that some users had more than one article so in our array, we had under same userid more than one record.
That means the number of elements in $aSortedLastNames and $aSortedFirstNames didn't match the number of elements of the main array, that's why array_multisort did not work.
Here is the new loop:
$aSortedNames = array();
foreach ($aOrderArticleExportData as $sUserId => $aUserData) {
$aArticleData = current($aUserData);
$aSortedNames[] = $aArticleData['lastname']. '_' . $aArticleData['firstname'];
}
array_multisort($aSortedNames, SORT_ASC, $aOrderArticleExportData);

Related

Is this the correct PHP Syntax for adding an associative array to an existing associative array.

I have three variables retrieved from a database and I would like the first variable to be the key for the second variable and for that second variable to be the key for the third variable. In essence a two-dimensional array.
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$unit_id = $row['id'];
$unit_code = $row['unit_name'];
$unit_description = $row['unit_description'];
$units = [$unit_id => $unit_code];
$units += [$unit_code => $unit_description];
}
return $units;
You can simply make like this
<?php
$unit_id = 'id';
$unit_code = 'unit_name';
$unit_description = 'unit_description';
$units[$unit_id] = [$unit_code=>$unit_description];
//$units[$unit_id][$unit_code] = $unit_description;
print_r($units);
?>
Live demo : https://eval.in/880865
Yess you can do this.
$array = [
'data' => 'my data'
];
now you can do this simply
$array['anotherArray'] = $anotherArray;
If "id", "unit_name" and "unit_description" are respectively the first, second and third value of the database, this is the code:
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$units[$row['id']][$row['unit_name']] = $row['unit_description'];
}
return $units;
If array consists of key, value parts (associative arrays), which your case is like that, you just need to:
$data[$key] = $value;
So in your case it would be:
$units[$unit_code] = $unit_description;
If your arrays' keys are indexed, then using array_push can do the job too:
array_push($units, $unit_description);

How to extract value from foreach loop by json_encode

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.

PHP arrays, getting multi-dimensional data from for reach

I've looked on stackoverflow for the answer, but no one explains it properly.
I have a while loop that works:
info = array();
while($get_info= mysql_fetch_array($info_result)){
$info['team_id'] = $get_info['team_id'];
$info['team_points'] = $get_info['team_points'];
}
And when I print out the array:
Array ( [team_id] => 26 [team_points] => 100 )
But my foreach returns an invalid argument.
foreach ($info as $info_mation ){
echo $info_mation['team_id'];
echo $info_mation['team_points'];
echo "<br/>";
}
I've tried many different ways but nothing works.
Thanks!
Problem is in fetching data from DB. Modify your while loop like this:
info = array();
while($get_info = mysql_fetch_array($info_result)){
$temp_info = array();
$temp_info['team_id'] = $get_info['team_id'];
$temp_info['team_points'] = $get_info['team_points'];
$info[] = $temp_info;
}
Now your foreach loop should work properly.
Here is a bit more explanation, if what you've seen so far doesn't make sense. When you do this:
$info = array();
while($get_info = mysql_fetch_array($info_result)) {
$info['team_id'] = $get_info['team_id'];
$info['team_points'] = $get_info['team_points'];
}
You are overwriting $info with each iteration of the while loop. So at the end of your loop, $info will only contain the last row of your query result.
This explains the result you see:
Array ( [team_id] => 26 [team_points] => 100 )
So when you iterate this array with
foreach ($info as $info_mation ){
echo $info_mation['team_id'];
echo $info_mation['team_points'];
echo "<br/>";
}
$info_mation will contain 26, and then 100, which are indeed invalid for foreach.
You need to create a multidimensional array rather than a one-dimensional array. You can do that by modifying your while loop slightly:
while($get_info= mysql_fetch_array($info_result)) {
$info[] = $get_info;
}
Doing it this way adds a new array element to the $info array with each iteration, rather than overwriting the same two elements repeatedly.
this is your code:
info = array();
while($get_info= mysql_fetch_array($info_result)){
$info['team_id'] = $get_info['team_id'];
$info['team_points'] = $get_info['team_points'];
}
change it to this:
$info = array();
while($get_info= mysql_fetch_array($info_result)){
$info[] = array(
'team_id' => $get_info['team_id'],
'team_points' => $get_info['team_points']
);
}
so, your $info variable contains all the array from the sql result you made.
foreach($info as $inf) {
echo $inf['team_id'];
echo $inf['team_points'];
echo '<br>';
}
and we're done! :)

Sort array according to value of key

I have one array which have the right order of the keys,
For example,
$array_keysorder=([0]=>"Fire",[1]=>"Sky",[2]=>"Third")
//Array i want to sort,after appending the order is messed up
$tosortarray=(['Sky']=>array(array()...),['Third']=>array(),['Fire']=>array())
//This is how i want the final array to look like
$Final=(['Fire']=>array(), ['Sky']=>array(array()...),['Third']=>array())
What about rebuilding the array?
Edit.. I added some commenting..
<?php
$array_keysorder[] = "Fire";
$array_keysorder[] = "Sky";
$array_keysorder[] = "Third";
print_r($array_keysorder);
$bad_array[Sky] = "data1";
$bad_array[Third] = "data2";
$bad_array[Fire] = "data3";
echo "<br>";
print_r($bad_array);
//This count cycles through the sort order, 0 = Fire, 1 = Sky, etc.
$key = 0;
//Cycle through array. $row isn't used.
foreach($bad_array as $row)
{
//$temp_val will store the key name ie "Fire".
$temp_val = $array_keysorder[$key];
//Create a organized array with the correct order of the keys
$good_array[$temp_val] = $bad_array[$temp_val];
//Increase the key to the next one.
$key++;
}
echo "<br>";
print_r($good_array);
?>

How can I create an array with key value pairs?

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'];
}
}

Categories