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.
Related
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! :)
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'))
I've looked for days and to no avail. I can't find a function which could add to an array with the key and value.
Here's why I need it: I need an array to store both the name of the owner and the type of the car. I'd like for the key to be the name of the owner and the type of the car to be the value and not have to use two arrays to contain something which one array can.
Here's my current code:
Function used to get $vehicleName
function carName($nakedCarString)
{
$cars=(separateString($array, $vehicleString));
return $cars[0];
}
The above code uses a vehicle string, gets the name of the car with an array and returns the name of the car in a string. Not an array.
Code(which requires code to add to array with key and value) which will be adding info to array
while($row = mysql_fetch_array($result))
{
$vehicleString = $row['Vehicle'];
$vehicleName = carName($vehicleString);
$seller = steamID2CommunityID($row['Auctioneer']);
$name = new SteamAPI($seller);
$sellername = $name->getFriendlyName();
}
The above code gets each row in a mysql table and foreach row it'd get the vehicle string, the name of the car from vehicle string using function above, the seller and the sellers name(in string, not array)
I'd need it so that it could add to an array($carIndex) with the key($sellername) and value($vehicleName). Any help?
You are overcomplicating this:
$cars= array();
while($row = mysql_fetch_array($result))
{
$seller = steamID2CommunityID($row['Auctioneer']);
$name = new SteamAPI($seller);
$sellername = $name->getFriendlyName();
$cars[$sellername] = carName($row['Vehicle']);
}
you mean
$carIndex[$sellerName] = $vehicleName;
I would not recommend you to use the name as a key in the array, as it might contain invalid characters, why don't you use a multi-dimensional array instead:
$cars = array();
while($row = mysql_fetch_array($result))
{
$array = array();
$vehicleString = $row['Vehicle'];
$array['vehicleName'] = carName($vehicleString);
$seller = steamID2CommunityID($row['Auctioneer']);
$name = new SteamAPI($seller);
$array['sellerName'] = $name->getFriendlyName();
$cars[] = $array;
}
Exmaple output:
Array (
[0] => Array
(
['vehicleName'] => "Ford"
['sellerName'] => "John Sr."
)
[1] => Array
(
['vehicleName'] => "Audi"
['sellerName'] => "Jane-Doe"
)
)
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'];
}
}
I am pretty new to php and could sure use some help understanding how to get my result the way I need it from a database query.
What I need is an associative array like this, 'bla'=>'bla'. What I am getting from my foreach loop is this from a print:
[0] => Array
(
[0] => test0
[name] => test0
[1] => 1
[customer_id] => 1
)
[1] => Array
(
[0] => test
[name] => test
[1] => 2
[customer_id] => 2
)
Here is my loop:
foreach($res as $key=>$val)
{
// have no idea..
}
Can someone please help me to format my results so that they are like 'index'=>'value'
Thanks for any help.
Here is a sample code that uses a foreach but yet pulls an association. I don't get it. I am thinking that my result set with the indexes are because I am not writing the loop correctly. Here is the code that uses the foreach
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}
}
Here is the part of the database class that I am using to fetch the results.
$returnArray = array();
$i=0;
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
if($row)
$returnArray[$i++] = $row;
}
mysql_free_result($result);
return $returnArray;
After using the code that was given to me to omit the index numbers, here is what I am now left with. Its close but not what I need.
Array
(
[id] => 1
[cust] => bobs auto
)
This is what the above line should read like
'1' => 'bobs auto'
What I am trying to do is to format the output for a JSON call for a suggestion box.
I cannot get this to work. Here is everything after my db connection.
$out_array = array();
foreach($items as $key=>$val)
{
if(is_int($key))
{
continue;
}
$out[$key['id']] = $val['cust'];
}
//echo'<pre>';
//print_r($out_array);
//echo'</pre>';
foreach ($out_array as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}
}
OK, I think I am coming down to the home stretch. I have what I need sort of. This is the code I have so far.
$out_array = array();
foreach($items as $key)
{
$out_array[$key] = $val;
//$out_array[$key['id']] = $key['cust'];
}
Notice that the commented line does not work, It outputs like the id twice but the line that isn't commented out works just fine. Here is the output from that.
Array
(
[8] =>
[FAT BURGER] =>
)
From this point, would I just use another foreach to iterate over the entire set of data? The array output you see above is from a print_r.
This is what I now have and it returns the correct association however, I must comment out the strpos condition to get any results back and I don't know why. Am I correct in nesting these foreach loops like I have?
$out_array = array();
foreach($items as $key)
{
// $out_array[$key] = $val;
$out_array[$key['id']] = $key['cust'];
foreach ($out_array as $key=>$value)
{
if (strpos(strtolower($key), $q) !== false)
{
echo "$key|$value\n";
}
}
}
So you don't want the numeric indexes in your array? You must be using mysql_fetch_array(), which returns your results with both numeric and string keys. Use mysql_fetch_assoc() to get an array with only the string keys (the string being the column name).
Try something like this. It works by skipping the integer indices, and putting the non-integer indices into an output array.
$out_array = array();
foreach($res as $key=>$val) {
if(is_int($key)) {continue;}
$out_array[$key] = $val;
}
EDIT:
$out_array = array();
foreach($items as $key=>$val)
{
if(is_int($key))
{
continue;
}
}
$out[$out_array['id']] = $out_array['cust'];
//echo'<pre>';
//print_r($out_array);
//echo'</pre>';
foreach ($out as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}
}
Assuming this is a MySQL database, the results, if more than one, are returned as a multidimensional array.
When you run the query:
$query = "SELECT * FROM Table WHERE ...";
$query = mysql_query($query);
while($info = mysql_fetch_assoc($query)){
//$info is now a single row, associative array
echo print_r($info);
}
the echo print_r displays the results the way you are looking for them now 'index'=>'value'
EDIT: based on comments.
If you absolutely CAN'T get rid of the mysql_fetch_array then you'll have to hack the code. It's not clean and I strongly advise refactoring but below is the code you'll need to create an array of field name indexes only from what you're given
$my_array = array();
$info = $data[0]; //grab the first row of your data set from the original question.
foreach($info as $index => $value){
if(!is_int($index)){
$my_array[$index] = $value;
}
}
The newly created $my_array will be in the format you're looking for.
You got this array from a query and result function from PHP, yeah?
If you were using mysql, it's actually easier to do it like below.
$query = mysql_query("SELECT * FROM dbname"); //Create the query to your database
while($data = mysql_fetch_array($query)) //Loop through our results from the query
{
echo($data['fieldname']."<br/>"); //echo out data through the loop
}
$ret = array();
foreach($rows as $row)
{
$ret[$row['id']] = $row['cust'];
}
$json = json_encode($ret);
echo $json;
// Prints something like:
//
// {1:'bob'}
Note the use of json_encode.
Ok, regarding my last question. I was incorrect in nesting the foreach loops. I also had a typo in my code. It is working, finally. Thank you to all that have helped me!