Create multidimensional array without double values - php

I have a array, from sql query with several colums.
One of this is text column with names of clients.
$data['obchody']= $this->audytp_m->audytpro_obch();
$data['obchody_wsp']=array();
From this I create new array, for next step of my program:
$I=0;
foreach ($data['obchody'] as $row)
{
if(array_search($row['nieruchomosc'], array_unique(array_column($data['obchody_wsp'], 'nieruchomosc'))) ==0)
{
$data['obchody_wsp'][$I]['nieruchomosc']=$row['nieruchomosc'];
$data['obchody_wsp'][$I]['AudytPROInformacjaOUsludze']=$row['AudytPROInformacjaOUsludze'];
$data['obchody_wsp'][$I]['AudytPROCzestotliwoscObchodow']=$row['AudytPROCzestotliwoscObchodow'];
}
$I++;
}
$I=0;
I use array_search to find value in new table ( column: nieruchomosc). And generally its work, but sametimes one or more of the value is multiplify :(
I don't know why:

OK, I find the error in code.
array_search returns index of row, and "==0" is logical error, 0 is first row in array.
After var_dump i found, when array_search not find value, return's "false".
This below code working now fine:
if( array_search($row['nieruchomosc'], array_column($data['obchody_wsp'], 'nieruchomosc'))===false)

Related

array isn't combining with loop in php

i've a array problem couldn't just solve it:
here's the code that is already in a foreach loop. i'm getting the $row->class_id value from this loop. it works fine and get me the total students row within an array and i preserved it in $total_student_of_this_class variable. i used another foreach loop for storing the result of first loop and then second loop and so on. but this loop gives only first loop result.
i need to combine the all array of total iteration of the loop.
$total_student_of_this_class =
$this->db->select('student_id')->where('class_id',
$row->class_id)->get('student')->result_array();
echo count($total_student_of_this_class);
// prints 2 in the first row of the output table and 5 in the second
row for me.
$total_student = array();
foreach ($total_student_of_this_class as $tt)
{
$total_student[] = $tt;
}
echo '<pre>';
print_r($total_student_of_this_class);
echo '</pre>'
echo count($total_student);
// prints only 2 outside the loop (not 7)
pls someone help me.
The problem here is seems to be with $total_student = array();: initializing array inside an other loop it always starts it from zero values array, so you get only results from one iteration inside it and doesn't collect all datas.
You can also look at array_merge php function.

PHP spontaneously creates associative array where indexed array is required - using PHP arrays with Highcharts

I'm using PHP to retrieve data from an SQL database to produce a stacked column chart in Highcharts. The idea is that I'm taking the following piece of code to retrieve values from my database. This code should generate an array which then gets encoded to JSON and passed to Highcharts; this code produces a single 'part' of a stacked column, and the index determines which vertical bar that part is in. (So in http://www.highcharts.com/demo/column-stacked, the index would represent which fruit, and the data in this series would represent one person/color.)
The issue is that when I run this code, instead of ending up with an indexed array of data grouped by category, such as
[12,13,14,15] where each item is a category, I end up with an associative array where the indexes I specified in the code are turned into a string key.
{"1":13,"0":12,"3":14, "2":13, "5":15}
Because my indexes are being interpreted as associative keys and not as the indexed locations of the data inside the array, the data is now being added to locations in the order that I retrieved the data, and not assigned to a location in the array based on the index I give. Highcharts assigns categories based on location in the array, and not on key, so all my data ends up in the wrong categories.
Is there a way to get PHP to treat my carefully collected indexes as indexes and not as keys, and add my data points in the location in the array indicated by the indexes? I'm kind of new to PHP, and Java and C++ - the languages I've worked with before - don't have associative arrays, so any help you can give me in explaining and fixing this undesired behavior would be much appreciated.
Code below.
$variable indicates what the data is being sorted into categories by, and $r is the variable representing the array of the SQL query, so $r['variable'] is the category of this data point, and $r['amount'] is the data point itself.
$found = -1;
//if this is the first set of data being collected
if (count($category['data']) == 0){
$category['data'][0] = $r[$variable];
$series1['data'][0] = floatval($r['amount']);
$count++;
$times1[0]++;
}
//if it's not the first set of data, find out if this category has been used before
else {
for ($x = 0; $x < count($category['data']); $x++){
if ($r[$variable] == $category['data'][$x]){
$found = $x;
break;
}
}
// if that category does not already exist, add it, and add the data
if ($found == -1) {
$times1[$count]++;
$category['data'][$count] = $r[$variable];
$series1['data'][$count] = floatval($r['amount']);
$count++;
}
else { //otherwise, add its data to the data already in the current category. This will eventually yield an average, with $times1[] as the divisor
$times1[$found]++;
$series3['data'][$found] = floatval((floatval($series3['data'][$found]) + floatval($r['amount'])));
}}
Go through with below code hope it will give some idea to resolve your problem --
<?php
$jsonstring = '{"1":13,"0":12,"3":14, "2":13, "5":15}';
$tempArr = json_decode($jsonstring, true);
asort(tempArr); // for sorting the array --
//run another foreach to get created an array --
$finArr = array();
foreach(tempArr as $key=>$val){
$finArr[] = $val;
}
$requiredjsonString = json_encode(finArr); // it will return your required json Array [12,13,14,15]
?>
Edit: I advice also set JSON_NUMERIC_CHECK flag in json_encode();

Result is empty after while loop

Why is this not possible? Is there some way I can make the resolut not to be empty?
$sqlAllInfo = "SELECT item1, item2 FROM example";
$resAllInfo = mysql_query($sqlAllInfo);
while($rowAllInfo = mysql_fetch_assoc($resAllInfo)){
echo $rowAllInfo['item1'];
}
$rowAllInfo = mysql_fetch_assoc($resAllInfo);
echo $rowAllinfo['item2'];
Thanks for your time
No, the result will always be empty after your while loop, because the while loop extracts all value from the result resource..the while loop continues looping while there is still information to extract, and will finish when it is empty or when an error occurs
if you ment to get the last entry
$rowAllInfo still contains the last entry ;)
You are looping through the result set using while until there are no more results left. The while loop exits when mysql_fetch_assoc returns false, because there are no more results. Calling mysql_fetch_assoc again still means that there are no more results.
This line:
while($rowAllInfo = mysql_fetch_assoc($resAllInfo)){
assigns a new value to rowAllInfo and afterwards checks whether it is still "true"-ish (as "true" as PHP can be ;-) )
Now, after the last row is fetched, mysql_fetch_assoc() will return false, which is then assigned to $rowAllInfo. As $rowAllInfo is now "false", the loop will not execute anymore, but - look - it's too late! You Variable already has the value false assigned to it.
Even after that, you call mysql_fetch_assoc() once again. But, as you have already fetched all rows within your loop, no more rows are left, and once again $rowAllInfo is set to "false".
So, whatever you are trying to do - this is probably not your way. A common way to achieve what I understand you are trying to do is the following:
$allRows = array();
while( $row = mysql_fetch_assoc($res) ) {
$allRows[] = $row;
}
// show the array we just created...
echo print_r( $arrRows, 1 );

mySQL loop, put the values into an array

I have the following function.
return $this->_blockPhoto ( $selected_screenshots, $this->aDataEntry['author_id']);
It requires that the variable $selected_screenshots is an array of values.
The problem is that I have to take the values from a mySQL look, that is reported below.
If there is only one value, everything works fine. But when there are more values in the DB, I cannot put all those values into the variable array.
In fact, since return $this->_blockPhoto ( $selected_screenshots, $this->aDataEntry['author_id']); is outside the mySQL loop, it gets only the first value of the loop.
So how do I store all the values from the mySQL loop into the variable? And not only the first value?
I tried to manually assign the array to the variable in the loop $selected_screenshots = array($qryrow1['media_id']); but it does not work and I do not think it has any sense :)
$qry1="SELECT * FROM modzzz_articles_screenshots WHERE media_id='".$selected_screenshots_ID."' AND entry_id='".$this->aDataEntry['id']."'";
$qryr1=mysql_query($qry1) or die("Error selecting: ".mysql_error());
while($qryrow1 = mysql_fetch_array($qryr1)) {
$selected_screenshots = array($qryrow1['media_id']);
} // END OF THE LOOK
return $this->_blockPhoto ( $selected_screenshots, $this->aDataEntry['author_id']);
Can anyone give me the solution, with code? I am really confused.
Thanks
Your code keeps overwriting $selected_screenshots with a new array each time. Instead, you want to append it:
$selected_screenshots = array();
while ($qryrow1 = mysql_fetch_array($qryr1)) {
$selected_screenshots[] = $qryrow1['media_id'];
}
You can save all the mysql values by looping through your results and appending them to the end of $selected_screenshots to do this please look below. Right now you are just assigning $selected_screenshots one value and neglecting the other values, so $selected_screenshots is having the last value that mysql returns.
This is covered http://php.net/manual/en/language.types.array.php under the heading 'Creating/modifying with square bracket syntax'

Help with getting first value of array in PHP

Stumped by this one:
I have a function that returns an array of folders in a given directory. When I iterate through the array, I can see all the items. However, if I try to print the first item, I get nothing:
function get_folders($dir) {
return array_filter(scandir($dir), function ($item) use ($dir) {
return (is_dir($dir.'/'.$item) && $item != "." && $item != "..") ;
});
}
$folders = get_folders(".");
$first_folder = $folders[0];
echo $first_folder; // returns blank.
Interestingly, if I don't filter out the "." and "..", then $first_folder does print ".". Can anyone explain this?
As noted in the manual: Array keys are preserved when using array_filter().
The keys are preserved from the call to scandir() which will include the . and .. directories, meaning your filtered array will start at 2 or more (whatever the key is for the first directory).
A simple fix would be to wrap the whole thing in array_values() to get the resultant array having keys starting from 0 and incrementing by one.
return array_values(array_filter(...));
If you don't actually care about the keys, then basic array functions could be of use like key or current.
From the array_filter manual:
Iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.
So, scandir($dir) gets you an array with . at key 0, thus if you later filter . out, there will be nothing at key 0 in the result.
If you want to know what the first key of the resulting array is, try the array_keys function.
EDIT: actually, salathe's suggestion to use array_values is better in your case than getting the keys from array_keys.
can you print the folders and see if there is some key you can get the first folder with as opposed to selecting the index of zero? It seems lke $folders[0] would work unless the entries are stored with a different set of indexes / keys.
Try doing a
print_r($folders)
to see if it outputs your first folder and all other folders as expected with the corresponding indexes you're looking for.
array_filter preserves array keys, so if the first two elements have been removed, then the "new first" element has an index of 2. To convert that into an array indexed starting from 0, use array_values:
return array_values(array_filter(scandir($dir), function ($item) use ($dir) {
...
As others have said, array_filter preserves the keys in the array. Given that initially the item '.' has key 0, the filtered array ends up not having any item with key 0 (you can verify this with print_r($folders). So this line:
$first_folder = $folders[0];
ends up generating an E_NOTICE saying that there is no key 0 in the array (having notices turned on would alert you to the cause of the problem immediately, I highly recommend it) and giving $first_folder the value null.
To get the first value of the filtered array, regardless of key, use reset:
$first_folder = reset($folders);
if($first_folder === false) {
echo 'No folders!';
}
else {
echo 'First folder: '.$first_folder;
}

Categories