aside from doing the actual work of iterating through an associative array, pushing a value into a new array and setting that equal the array of remaining fields, is there an array function built into PHP that would do something like this?
if so, what is it?
i would be changing the following:
Array
(
[0] => Array
(
[0] => TEST //Name (Database column name
[1] => 12430 //ID (Database column name
[2] => Y //Save (Database column name
[3] => 100 //Wert (Database column name
)
into something like this:
Array
(
[12430] => Array
(
[Name] => TEST
[Save] => Y
[Wert] => 100
)
i work with while-loop:
....
while( $row = mysql_fetch_assoc($ergebnis) ) {
....
}
I think that you are going to have to iterate through the array. There may be a function here that could shorten the code by about a line, but I doubt it will make a noticeable difference to the readability and efficiency of your code.
So I would iterate through the array if I were your, quite short and simple.
$new_array = array();
while( $row = mysql_fetch_assoc($ergebnis) ) {
$new_array[$row[1]] = $row;
unset($new_array[$row[1]]);
}
Note that the mysql_ functions have been deprecated in PHP and you should be using mysqli_ or PDO instead, as it is more stable and secure.
Also, as #CBroe said, the mysql_fetch_assoc function will return the second part of your desired result already. The equivalent in PDO would be $query->fetch(PDO::FETCH_ASSOC);
Good luck!
Alter your query and add GROUP BY ID at the end.
Related
I have a multidimensional array like this:
Array (
[0] => Array
(
[time] => 1364685993
[memberid] => 131
)
[1] => Array
(
[time] => 1364685994
[memberid] => 133
)
[2] => Array
(
[time] => 1364685995
[memberid] => 141
)
)
and a single-dimensional array like this:
Array (
[0] => 131
[1] => 141
[2] => 191
[3] => 205
)
Now I want to remove all Sub-arrays from multidimensional arrays that DOES NOT contain the memberid value from normal array ?
In this case only Subaray[1] to be removed from multidimensional array as it's 'memberid' key value (133) doesn't show in normal array. Those arrays are actually pretty big, so I am not sure what would be fastest way to do it ?
$normalArray = array_flip($normalArray);
$multiDimArray = array_filter($multiDimArray, function ($elem) use ($normalArray) {
return isset($normalArray[$elem['memberid']]);
});
Requires exactly two iterations, one over each array. Key lookups using $normalArray[$elem['memberId']] are blazingly fast. May have some memory overhead due to the functional nature and copies of arrays, use a traditional loop and unset if that's an issue.
First, I would flip the $nomal array to get constant lookup time into the array, like this:
$normal = array_flip( $normal);
Then, you just have to filter the $multidimensional_array by the $normal array with a simple lookup:
$filtered = array_filter( $multidimensional_array, function( $el) use( $normal) {
return isset( $normal[ $el['member_id'] ]);
});
Don't have access to development resources at the moment to test but this should work.
foreach($members as $member => $property) {
if (!in_array($property['member_id'], $id_array)) {
unset($members[$member]);
}
}
$id_array is the 1-dimensional matrix (array) you've put in your question.
Instead of filtering the database results after the fact you may want to use the single-dimensional array in the database query itself.
We do not know what the query, you are using, looks like, but something along these lines would do it:
// The ids from the file
$use_ids = array(131, 141, 191, 205);
// Create a list for the IN clause
$ids = '(' . implode(',', $use_ids) . ')';
// Create the query
$query = <<< SQL
SELECT time, memberid
FROM some_table
WHERE ...
AND memberid IN {$ids}
ORDER BY time
SQL;
// Execute the query, etc.
It is always a good idea to let the SQL handle as much filtering of content as possible.
The above searching I want with minimum number of code and with best serach performance.
I want to generate an array from this above array by putting logic like:
ALL "EMA" key values of array should not be allowed to match with "JACKSON" key values. Similarly all "JACKSON" key values of the same array are not allowed to fall in any value of "EMA" key. So the resulting array would be like shown below:
Array
(
[0] => Array
(
[EMA] => A
[JACKSON] => B
)
[2] => Array
(
[EMA] => D
[JACKSON] => E
)
)
I want to know the best approach with lesser code to achieve this. The method I have used seems so lengthy. I want a shorter and robust approach.
I think this might be a solution:
$emas = array();
$jacksons = array();
foreach($array as $element){
$emas[] = $element['EMA'];
$jacksons[] = $element['JACKSON'];
}
//array_intersect returns the common values in the arrays as an array
if(!empty(array_intersect($emas, $jacksons))){
echo 'array is invalid!';
}
I am using an API which has a lot of data inside lots of arrays which as you may know can be quite confusing.I am relatively new to API's and this one in particular has no documentation.
My code below is grabbing the recent_games() function which is pulling the whole API then I am using foreach loops to get inside the data.
$games = $player->recent_games();
foreach($games['gameStatistics']['array'] as $key => $gameStatistic) {
$game_date[strtotime($gameStatistic['createDate'])] = $gameStatistic;
}
// order data
krsort($game_date);
foreach ($game_date as $game => $data) {
$statistics[$data] = $data['statistics'];
}
I am getting errors such as illegal offset for:
$statistics[$data] = $data['statistics'];
Is there a way to continue down the nesting of arrays ($game_date) to get to the data that I need?
Let me know if you need more info.
Thanks
EDIT more info:
The first foreach loop at the top loops a unix timestamp key per game. Looks like this:
[1370947566] => Array
(
[skinName] => Skin_name
[ranked] => 1
[statistics] => Array
(
[array] => Array
(
[0] => Array
(
[statType] => stat_data
[value] => 1234
)
[1] => Array
(
[statType] => stat_data
[value] => 1234
)
As you can see its quite nested but I am trying to get to the individual statistics array. I hope that helps?
$statistics[$data] = $data['statistics'];
There is absolutely no way this line is correct.
The right hand side uses $data as if it were an array, indexing into it. The left hand side uses $data as a key into an array. Since the only valid types for keys are strings and integers, $data cannot satisfy the requirements of both expressions at the same time -- it cannot be an array and a string or integer.
It's obvious from the error message that $data is in fact an array, so using it as $staticstics[$data] is wrong. What do you want $statistics to be?
For some reason my array I am returning is not what I expect. Could someone explain to me why I am getting the current results, and what I can do to fix it? Here is the code in question:
public static function getProduct($_row, $_value)
{
$stmt = _DB::init()->prepare("SELECT pid, name, quantity, price, cost
FROM products
WHERE $_row = ?"
);
if($stmt->execute(array($_value)))
{
while ($row = $stmt->fetch())
return $row;
}
}
$product = Class::getProduct('pid',1);
print_r($product);
When I print the following array I am getting two results per row like so:
Array ( [pid] => 1 [0] => 1 [name] => Boondoggle [1] => Boondoggle [quantity] => 12 [2] => 12 [price] => 9.9900 [3] => 9.9900 [cost] => 12.9900 [4] => 12.9900 ) Boondoggle
I was only wanting to show the associative results. What is wrong with my function?
From the looks of it you are using PDO to communicate with your DBMS. The PDOStatement::fetch() method's first argument is a parameter to tell it what to return. By default it returns each column in both name format and numbered index format to allow iterating through columns easier. To just get the column names as indexes, you can pass it PDO::FETCH_ASSOC to your call. So the fetch statement would look like this:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)
See here for more details:
http://www.php.net/manual/en/pdostatement.fetch.php
Pass PDO::FETCH_ASSOC to your fetch call:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
edit: I'm just assuming you're using PDO, of course
By default mysql_fetch_array returns numeric and associative array togeather. This function is useful for reading, while you can get values
either by statement :
echo arr[1]; //circle
or
echo arr["shape"]; //circle
I am new to PHP and I run into the troubles when I wanted to change the values of that fetched array:
arr[1] = square;
I supposed that arr["shape"] will be 'square' too, but I was wrong. arr["shape"] still remains 'circle'.
Obviously you have to change both values to 'circle'.
Moreover: I wrote a funcion which should return changed shape array, (which is 2D array). I got different outcomes, if I used the first or
the second line of code.
function ChangeShape($arr)
{
for ($i=0; $i<$count($arr); $i++)
{
1. $arr[$i]["shape"] = 'square'; // fail to return changed $arr - it is (probably) reference to number counterpart
2. $arr[$i][2] = 'square'; // this WILL return changed $arr
}
}
return $arr;
}
My questions:
1. is there any technique in PHP by which I can change both values at once?
2. in my app I use assoc nicknames to access array values. But when it is not possible to change numeric alias at the same time, what is
the easiest way to do it?
thank for reading this to the end... hope you answer.
Thanks a lot.
If you just want the data in a simple array once you grab it, you can always just simplify it by putting it in a few array:
$query = "SELECT * from myTable";
$result = mysql_query($query) or die(mysql_error());
$newArray = array();
$i=0;
while($row = mysql_fetch_array($result)){
array_push( $newArray, $row[$i]['name'] );
}
print_r($newArray);
$newArray[4] = "some other value than what came from the db";
print_r($newArray);
It doesn't seem super clear why your data is coming back as complicated as it seems to be, but this might help clear it up.
Do you really need to fetch numeric index? At least based on what you've posted it seems like you just want to call mysql_fetch_assoc to get an array with just the associative version.
The "aliases" in the array returned by mysql_fetch_array aren't really aliases... it just inserts it twice into the result array, once with the numeric index and once with the name of the column. The only way to change them both is to assign them both the desired value.
See this example and maybe it will make sense why its not working. Its not a reference or it would be working. If you had to have this functionality, you could build your array like this:
<?
$a='dog';
$b='cat';
$arr=array ('a' => &$a, 1 => &$a,'b' => &$b,'2' => &$b );
print_r($arr);
$a='horse';
print_r($arr);
$arr[1]='cow';
print_r($arr);
Results:
Array
(
[a] => dog
[1] => dog
[b] => cat
[2] => cat
)
Array
(
[a] => horse
[1] => horse
[b] => cat
[2] => cat
)
Array
(
[a] => cow
[1] => cow
[b] => cat
[2] => cat
)