Hy every one I have this problem with an array I start like this...
$name = array($_POST['names']);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
$nameId[] = array('ids' => $row['id'] );
}
which gives me arrays like this..
$name:
array('0'=>'name1,name2,name3')
$names:
array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
how can I bring this in an string/form like this..
array('0'=>'61,6,1')
The idea is to save the ids to the Database.
Or is the a better more efficent way to get names from a form compare them with a database and get the ids back to save them to the Database?
many thanks in advance.
Change your assignment to this:
$nameId[] = $row['id'];
$name = array(name1,name2,name3);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
//below line changed
$nameId[] = $row['id'] ;
}
$string = implode(',',$nameId);
Try this :
$array = array(0=>array(0=>'61'),1=>array(0=>'6'),2=>array(0=>'1'));
$result = implode(",",call_user_func_array('array_merge', $array));
Please note : Here all are numeric keys, so change your code to :
$nameId[] = array($row['id'] ); , remove key 'ids' from here
Output :
61,6,1
Thats what I think
$nameId[] = $row['id'];
$stringId = implode(',',$name);
Use following function that will loop through array and find ids key and merge it into other array and after that when you calling this function it will impload it.
function CustomFindJoinArray( $needly, $array )
{
$results = array();
foreach ( $array as $key => $value )
{
if ( is_array( $value ) )
{
$results = array_merge($results, foo( $needly, $value ));
}
else if ( $key == $needly )
{
$results[] = $value;
}
}
return $results;
}
echo implode( ",", CustomFindJoinArray( "ids", $your_array ) );
where $your_array will be array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
OR More simple
foreach ($your_array as $key => $ids) {
$newArray[] = $array[$key]["ids"];
}
$string = implode(',', $newArray);
$ids = array();
foreach($nameId as $curr) {
$ids[] = $curr['ids'];
}
$str = "(".implode(",",$ids).")";
Related
I cannot solve this seeming simple problem. I have the following simple code and all I want is to echo the result of $ATL5_Alert_query and separated by a comma (,):
$ATL5_Alert_query = mysql_query("SELECT `Mobile` FROM `dbo_tech_name` WHERE `AlertLevel`= 1");
$dataset = array();
while ($data = mysql_fetch_array($ATL5_Alert_query))
{
$dataset[] = $data;
}
echo implode (",", $dataset);
However, I'm getting "Notice: Array to string conversion "...
In your code $data is array as well, so $dataset becomes an array of arrays, which you cannot concatenate. You should get the searched value by this:
while ($data = mysql_fetch_array($ATL5_Alert_query))
{
$dataset[] = $data['Mobile'];
}
or:
while ($data = mysql_fetch_array($ATL5_Alert_query))
{
$dataset[] = $data[0];
}
or:
while ($data = mysql_fetch_assoc($ATL5_Alert_query))
{
$dataset[] = $data['Mobile'];
}
If you however cannot change this, and already have your $dataset array, you can implode it like that:
echo implode(',', array_map(function($a){
return $a['Mobile'];
},$dataset));
[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]
I got an object like above. The thing I want to is select the object that's id is 1 for example. Like
select * from object where id=1
with SQL
How to do it?
I hope i got your question right.
Try the following
<?php
$array = json_decode('[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]');
foreach( $array as $v ) {
if( $v["id"] == 1 ) {
echo "I am ID 1";
break;
}
}
Decode your object (http://php.net/manual/it/function.json-decode.php) and then traverse your array with a foreach checking the id value inside of it with an if statement.
$obj_to_array = json_decode($json_object);
$target = '';
foreach($obj_to_array as $row){
if($row['id'] == 1)
$target = $row;
}
// $target holds your row with id = 1
$data = '[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]';
$data = json_decode($data);
$id = 1;
$key = 'id';
$data = array_filter(
$data,
function($value) use ($key, $id) {
return ($value->$key == $id);
}
);
var_dump($data);
Decode the object using json_decode. Use the code below
<?php
$json='[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]';
$p = json_decode($json,true);
$l=count($p);
for($i=0;$i<=$l;$i++){
$id=$p[$i]["id"];
if($id==1){
print_r($p[$i]); // WIll print the id if 1
}
}
Hope this helps you
I have been trying to convert the fields from a mysql_fetch_array (that are urlencoded) to urldecode before converting to JSON (json_encode)
Here's what I'm working with that doesn't work:The output is still urlencoded
$query = "SELECT * FROM table WHERE tableId=$tableId";
$result = mysql_fetch_array(mysql_query($query));
foreach($result as $value) {
$value = urldecode($value);
}
$jsonOut = array();
$jsonOut[] = $result;
echo (json_encode($jsonOut));
Any ideas?
yeah....! you're not updating $result with the value returned by the function. $value needs to be passed by reference.
foreach($result as &$value) {
$value = urldecode($value);
}
or
foreach($result as $i => $value) {
$result[$i] = urldecode($value);
}
when you do this...
foreach($result as $value) {
$value = urldecode($value);
}
The result of the function is lost at at iteration of the foreach. You're trying to update each value stored in $result but that's not happening.
Also take note that the code only fetches one row from your query. I'm not sure if that's by design or not.
Try:
$query = "SELECT * FROM table WHERE tableId=$tableId";
$result = mysql_query($query);
$value = array();
while($row = mysql_fetch_array($result))
$value[] = urldecode($row);
}
$jsonOut = array();
$jsonOut[] = $result;
echo (json_encode($jsonOut));
I'm trying to store my mysql query in an array like this :
$arr = array ( "field1"=>"value" , "field2"=>"value" , "field3"=>"value" , ... );
I've tried this but don't work like I need :
$row_selectProduct = array();
$sResult = $db->query( 'SELECT * FROM tbl' )
while ( $aRow = $sResult->fetch_assoc() )
{
$sInfo = $sResult->fetch_field();
// General output
$row_selectProduct[ $sInfo->name ] = $aRow;
}
$sResult->close();
Thx for help
EDIT :
Sorry for misunderstanding...
I'd like to name keys by the field name in database.
I try to reproduce this :
$result = array();
while ($row_selectProduct = mysql_fetch_assoc($selectProduct));
{
$row_array= array();
$row_array['field_name1_In_DB'] = $row_selectProduct['field_name1_In_DB'];
$row_array['field_name2_In_DB'] = $row_selectProduct['field_name2_In_DB'];
$row_array['field_name3_In_DB'] = $row_selectProduct['field_name3_In_DB'];
$row_array['field_name4_In_DB'] = $row_selectProduct['field_name4_In_DB'];
$row_array['field_name5_In_DB'] = $row_selectProduct['field_name5_In_DB'];
...
array_push($result,$row_array);
};
Using PDO connection functions, it's quite simple --
foreach($db->query('SELECT field_name1,field_name2 FROM table') as $row) {
echo $row['field_name1'].' '.$row['field_name2']; //etc...
}
Here's a good tutorial for PDO in PHP if you want more.
while ( $aRow = $sResult->fetch_assoc() )
{
foreach($aRow as $fieldname => $fieldvalue) {
$row_selectProduct[$fieldname] = $fieldvalue;
}
}
but you will overwrite your $row_selectedProduct with every record and the var at the end will only have stored the last record
if you would like to have all results in one array you should:
$results = array();
while ( $aRow = $sResult->fetch_assoc() )
{
$results[] = $aRow;
}
if you know that there will be only one result you need only:
$result = $sResult->fetch_assoc();
Is there function encoding an associative array to use in a mySQL INSERT command?
This way you could do:
$array = mysql_fetch_assoc($result);
$array['key'] = 'updated_value';
mysql_query('INSERT INTO table ' . mysql_encode_assoc($array));
mysql_encode_assoc input:
array(
'name' => 'bob',
'vehicle' => 'car'
)
mysql_encode_assoc output:
'(name, vehicle) VALUES(bob, car)'
There is now:
function mysql_encode_assoc($array) {
$kenc = Array();
$venc = Array();
foreach($array as $k=>$v) {
$kenc[] = "`".mysql_real_escape_string($k)."`";
if( $v === null) $venc[] = "NULL";
else $venc[] = '"'.mysql_real_escape_string($v).'"';
}
$keys = "(".implode(",",$kenc).")";
$vals = "(".implode(",",$venc).")";
return $keys." VALUES ".$vals;
}
There's no built in function that I'm aware of. But you can quite easily make on using array_keys() and array_values().
No built-in function.
$sql = array();
foreach ($anArray as $f=>$v) $sql[] = "`{$f}`" = "'".mysql_real_escape_string($v)."'";
$query = "INSERT INTO table SET ".join(",", $sql);