PHP Array within array issue - php

I have an array like the one given below:
{
"quantity":"1",
"product_id":"41",
"option[232]":"28",
"option[231][]":"25"
}
I run the above in a foreach loop as $key => $value. But when I try to concatenate them into a string, I get an Array to String conversion error.
Eg: $result = $this->db->query("SELECT a.quantity quantity, b.name optionname FROM " . DB_PREFIX ."product_option_value a, " . DB_PREFIX ."option_value_description b WHERE a.option_value_id = b.option_value_id AND a.product_option_id=".$key." AND a.product_option_value_id=".$value." AND a.product_id=".$product_info['product_id']." AND a.subtract=1");
When I remove the last entry of "option[231][]":"25", it works fine. Is there anyway I can convert the "option[231][]" to "option[231]".
I am posting to a php page via json.
Thanks

Just use the print_r function to convert the multi-dim array, e.g.
option[231] = print_r(option[231], TRUE);
or, if you don't like the resulting syntax, nest a foreach loop within the existing foreach loop which executes when the variable is an array, e.g.
if(is_array(option[$x])){
$y = '';
foreach(option[$x] as $value){
$y .= $value;
}
option[$x] = $y;
}

Related

When I try to access to array items I only get the 1. one

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.

Adding arrays to a php variable

I am using PDO in order to select some values from my database.
For each iteration of my $teachArray, I store the selected array into my $language_id variable. I then get rid of any empty array that I have inside my $language_id and assigning it to my $NoEmptyArray_language_id However, I am only storing the last array inside of $language_id in $NoEmptyArray_language_id.
I would like to concatenate every array in $language_id into $NoEmptyArray_language_id.
I cannot use $NoEmptyArray_language_id .= $language_id; since it will give me an error: Array to String conversion
Here is my simple query.
$sqlFindId = "SELECT language_id
FROM language_skill
WHERE person_id = :person_id AND language_learning = :language_learning AND language_id = :language_id";
$NoEmptyArray_language_id = "";
foreach ($teachArray as $dataTeach)
{
$query = $handler->prepare($sqlFindUser);
$query->bindValue(':person_id', $_SESSION['person_id']);
$query->bindValue(':language_learning', 1);
$query->bindValue(':language_id', $dataTeach);
$query->execute();
$language_id = $query->fetchAll(PDO::FETCH_COLUMN, 0);
if ( count( $language_id ) != 0 ) {
$NoEmptyArray_language_id .= $language_id;
}
}
print_r($NoEmptyArray_language_id);
You have to define $NoEmptyArray_language_id = array();
Also change code with $NoEmptyArray_language_id[] = $language_id;
Now you have array with values in $NoEmptyArray_language_id.
If you want to get string convert this array to string using implode function.

Conditional where variable array is not empty, but has NULL values

I have the following problem in my php function:
$items is an array. It is never empty, But sometimes it has only has NULL values which returns an array value of [0]. How do I convert the conditional to say: If $items is not empty and if the $items array does not return a value of [0], then do this. . . ?
Thanks.
$items = Items_Model_Item::findBy(array('where' => new JO_Db_Expr('item.id IN (SELECT id FROM dbtable WHERE challengeId LIKE ' . Helper_Db::quote($challengeIDPLUS['code']) . ')')));
if (!empty($items)) {
foo
} else {
bar
}

how to pass json array to select query

I have json array as below
$q=[{"con0":0},{"con1":1},{"con2":2}]
I want to pass this array to select query where query is as follows
$query="select * from table_name where con0='0' and con1='1' and con2='2'";
Shall we use json array to create this query?
The two tricks are to turn the json into a php array via json_decode and then use reset() and key() functions to get the column and condition. Here is the live example:
http://ideone.com/wp1kb1 you can read more about key http://php.net/key and reset http://php.net/reset
<?php
$q='[{"con0":0},{"con1":1},{"con2":2}]';
$ar = json_decode($q, true);
$where = array();
foreach ($ar as $condition) {
$value = reset($condition);
$column = key($condition);
$where[] = " `$column` = " . (int) $value;
}
$whereString = implode(' AND', $where);
$query="select * from table_name where $whereString";
echo "\n $query \n";
Use json_decode to make this an object/array and then use a loop to make a string for that and append to the sql query.
Loop the JSON decoded data inside a foreach, then grab the key-value pair , store them in an array and after the end of the loop, do an implode() on the array with AND and now pass the string to your query as shown.
$json='[{"con0":0},{"con1":1},{"con2":2}]';
$qstr=array();
foreach(json_decode($json,true) as $k=>$arr)
{
$qstr[]="`".key($arr)."`"." = ".$arr[key($arr)];
}
$qstr = implode(' AND ',$qstr); //looks like `con0` = 0 AND `con1` = 1 AND `con2` = 2
$query="select * from table_name where ".$qstr;

PHP Multi Dimension Array Assignment

I need to fill a multidimensional array and here is my code I have so far for it.
while($num > $i)
{
$default[$i]=0;
$defaultcounter=0;
$default2[$i]=0;
$default3[$i]=0;
$query="Select * from `issues` WHERE `app`='" . $applist[$i] . "'" . "AND `startmonth`='". $month ."' ORDER BY `id` ASC";
$result=mysql_query($query);
while($row = mysql_fetch_array($result))
{
$downtime[$i]+=$row['duration'];
$default2[$i]++; //Number of Incidents Variable
$defaultcouinter++;
$times[$i] = array();
$times[$i][$defaultcounter[$i]]=$row['startday'].$row['starttime'];
}
$appavail[$i]=100 -(ceil($downtime[$i] * 100 / $totaltime));
$default[$i] = (ceil($downtime[$i] / $defaultcounter));
$i++;
}
Apparently I am not doing the array assignment correct. I need to to have my number of rows counted with the $i variable outside of my while then inside the while the defaultcounter will be keeping up with the column. I tried just doing a $time[$i][defaultcounter] and it didn't like it. Whats the proper syntax for assigning a multidimensional array?
Thanks
$times[$i] = array() should be out (before) the while loop unless you want it redefining $times as an empty array in each iteration (reseting values). Apart from that, you're assigning the values correct, although it looks a bit odd (not sure what you want to achieve there). This are the general formulas, should give you an idea:
$array[] = $subarray;
$array[$subarray] = $value;
$array[$subarray][] = $value;
$array[$subarray][$i] = $value;

Categories