I have two dimensional array, and I got needed result.
Now I need to insert it into db.
If the situation is [[]], that is one row in db and has specific number in db (it should start with 1).
If the situation is [[] , []], in that case values in brackets are dimension, each bracket is row, but they have the same name, for ex 2.
If there are more brackets inside [[] , [], [], []], in this case we will have 4 rows with the same name.
My database looks like
ID | DIMENSIONS | NAME
ID - auto increment
DIMENSIONS I take from below.
For ex.
[[12500,10]] - is one row, and for NAME it will have number 1.
[[12500,8],[6400,2]] - this is six element in array below. It will have two rows in database, and will have NAME 6.
echo json_encode($pak); // produces output below
"[[[12500,10]],[[12500,10]],[[12500,10]],[[12500,10]],[[12500,10]],[[12500,8],[6400,2]],[[6400,10]],[[6400,10]],[[6400,10]],[[6400,10]],[[6400,10]],[[6400,10]],[[6400,10]],[[6400,10]],[[6400,10]],[[5558,10]],[[5558,10]],[[5558,8],[4600,2]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,6],[4500,4]],[[4500,10]],[[4500,10]],[[4500,10]],[[4500,10]],[[4500,8]]]"
I got stuck here, any help is appreciated.
We can achieve it by Recursion.
But here I didn't use recursion (Because I am not good at that)
I haven't tested properly, so please go through it carefully. let me know if it has any problem.
$data = "[[[12500,1]],[[12500,2]],[[12500,3]],[[12500,4]],[[12500,5]],[[111111,6],[22222,6]],[[6400,7]],[[6400,8]],[[6400,9]],[[6400,10]],[[6400,10]],[[6400,10]],[[6400,10]],[[6400,10]],[[6400,10]],[[5558,10]],[[5558,10]],[[5558,8],[4600,2]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,10]],[[4600,6],[4500,4]],[[4500,10]],[[4500,10]],[[4500,10]],[[4500,10]],[[4500,8]]]";
$decoded = json_decode($data);
$namedArray = fix_name($decoded);
$insertArray = arrange_array($namedArray);
echo "<pre>";
print_r($insertArray);
echo "</pre>";die;
// Fix the Name first
function fix_name($decoded)
{
$number = 1;
foreach ($decoded as $key=> $value) {
$value['name'] = $number;
$insertArray[] = $value;
$number++;
}
return $insertArray;
}
function arrange_array($namedArray)
{
$insertArray = [];
foreach ($namedArray as $array) {
if (count($array) > 2) {
$name = $array['name'];
unset($array['name']);
foreach ($array as $key => $value) {
$array[$key]['name'] = $name;
}
foreach ($array as $arr) {
$insertArray[] = arrange($arr);
}
} else {
$temp['DIMENSIONS '] = $array[0];
$temp['NAME'] = $array['name'];
$insertArray[] = $temp;
}
}
return $insertArray;
}
function arrange($array)
{
$temp = [];
$temp['DIMENSIONS'] = [$array[0], $array[1]];
$temp['NAME'] = $array['name'];
return $temp;
}
Process:
First: Fix the names
Next: If count > 2 (because "name" key was added in previous function so will have minimum two )
then array in different way
else
key 0 as DIMENSIONS and key name as NAME
NOTE: There are other ways to achieve it but for quick fix I gave this.
I have 2 foreach loop's where i get new results from my first db and i have second foreach where i get data from second db
My first foreach code is:
foreach($_existing_data_result as $result) {
echo $result->name.'<br>';
}
second foreach:
foreach($_new_data_result as $resultNew) {
echo $resultNew->name.'<br>';
}
I need to check on second foreach if result exist in first then ignore this result, i tried it with in_array()but i always see double names...
Second foreach, change it to this:
foreach($_new_data_result as $resultNew) {
if (!in_array($resultNew,$_existing_data_result))
echo $resultNew->name.'<br>';
}
This will work assuming that entire $resultNew object exist in $_existing_data_result and is identical.
//Use array_diff instead. Like
$new_array = array_diff($_existing_data_result, $_new_data_result);
First get all names from the first array:
$names = array_map(
create_function('$object', 'return $object->name;'),
$app_items);
Then in second foreach check if the name exists in names array:
foreach($_new_data_result as $resultNew) {
if(!in_array($resultNew->name, $names) {
echo $resultNew->name.'<br>';
}
}
$names = array();
foreach($_existing_data_result as $result) {
echo $result->name.'<br>';
$names[$result->name] = 1;
}
foreach($_new_data_result as $resultNew) {
if (!isset($names[$resultNew->name])) {
echo $resultNew->name.'<br>';
}
}
I wish to run a foreach on a load of ID's.
However each of the items in the foreach is a select query and if it finds more ID's they need to be added to the array that is being run in the foreach.
E.g
$ids = array();
foreach($ids as $id)
{
SELECT id FROM table WHERE otherid = $id;
foreach ($query2->result_array() as $row)
{
array_push($array, $row['id']);
}
}
This is obviously pseudocode so no need to correct my SQL etc. I just need for the foreach to continue if it finds more ID's.
Possible?
I have tried adding an & here -> foreach($ids as &$id) as somebody else on here has suggested in a similar question. This doesn't seem to work.
foreach actually makes a copy of your array to loop though, you will need to use while.
while(list($id_key, $id) = each($ids)){
//your code
$ids[] = $row[id];
}
You should simply be able to just reference the original array ie
foreach ($query2->result_array() as $row)
{
$id[] = $row;
}
This will automatically assign an auto incremented key to the the new array element and add it to the $id array. I assume this is what you are after.
Try to iterate with a variable:
$ids = array();
$i = 0;
while ($i < count($ids)) {
$query2->query(SELECT id FROM table WHERE otherid = $ids[$i]);
foreach ($query2->result_array() as $row)
$ids []= $row['id'];
$i++;
}
For similar problems, I have always used two different arrays. Such code can run a query for every id only one time. I don't think it would be possible with only one array+foreach;
The following code is pretty simple. It keeps finding new ids until there are no new ids.
$ids = array();
$new = array();
$new = $ids;
do {
foreach($new as $n) {
$new = array();
//// HERE PUT YOUR CODE TO RUN A QUERY AND MAYBE PUSH A NEW ID TO $new \\\\
}
$ids = array_merge($ids,$new);
} while (count($new)!==0);
I am fetching data from my DB and they look like this:
[{"0":"1","key-1":"1","1":"1","key-2":"1","2":"1","key-3":"1","3":"1","key-4":"1"}]
where the key-1 are the name of the column. (I only have one entry so).
I want to extract only the column values and save them into a new array that will output like this:
{"key-1":"1","key-2":"1","key-3":"1","key-4":"1"}
I want it to look exactly like this and not : [{"key-1":"1","key-2":"1","key-3":"1","key-4":"1"}]
I tried this:
$cart["key-1"]=$output["key-1"];
where $output is the outcome of the DB that shown first (the one with []).
and the $cart is the new array I want.
Both are declared as:
$cart=array();
$output=array();
and $output[]=$row where row is the result of the DB fetch. How to do it?
Here's one way to do it, I've substituted the database row for a string here, and made use of json_decode() and json_encode()
$data = '[{"0":"1","key-1":"1","1":"1","key-2":"1","2":"1","key-3":"1","3":"1","key-4":"1"}]';
// convert to an array
$data = json_decode($data, true);
// create new array here
$cart = array();
for ($i = 0; $i < count($data); $i++)
{
foreach ($data[$i] as $k => $v)
{
if (strpos($k, 'key') !== FALSE)
{
$cart[$k] = $v;
}
}
}
echo $cart['key-1'] . '<br/>';
echo json_encode($cart);
Output:
1
{"key-1":"1","key-2":"1","key-3":"1","key-4":"1"}
This is a very chaotically asked question.
From what I gathered you want maybe this..?
$cart=array();
foreach ($output as $index=>$value){
if stripos($index,"key-"){
cart[$index]=$value;
}
}
Use mysql_fetch_assoc() to get only column names ;)
while ($row = mysql_fetch_assoc($result_of_query))
{
echo $row['key-1'];
echo $row['key-2'];
}
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!