PHP change array values to create new array - php

this way how i get array from db:
$sql = "SELECT * FROM table_name";
$query = mysqli_query($conn, $sql);
$db_array = array();
// start fetch for words
if (mysqli_num_rows($query) > 0){
while ($row = mysqli_fetch_assoc($query)){
$db_array[] = $row;
}
}
My array looked like this:
Array
(
[cat cute] => animal#cute animal
[cat women] => film
)
How to add '{' and '}' to all values?
I wish i can get new array like this:
Array
(
[cat cute] => {animal#cute animal}
[cat women] => {film}
)
It's hard for me, i am new in php development.

Try this,
$arr = array
(
'cat cute' => 'animal#cute animal',
'cat women' => 'film'
);
array_walk($arr, function(&$item){
$item = '{'.$item.'}';
});
print_r($arr);
Here is the link for array_walk()

Since you want a new array, try this:
<?php
array_map(function($value)
{
return '{' . $value . '}';
}, $arr);
array_walk() in rahul_m's answer modifies your array, while array_map() creates a new one.

Related

How to using implode from looping table in PHP?

I get error
Array to string conversion
when to implode looping from table
$sql = $this->db->query('select * from TEST');
foreach ($sql->result() AS $row){
$array[] = array('id' => $row->id);
$implode = IMPLODE(',',$array);
}
//This is I'm get data from other database server(SQL server) where in 'id' from database test(local database)
//and result query i will save to table test3(database server local)
$query = $db2->query("SELECT * FROM test2 WHERE id IN($val)");
$result = array();
foreach($query->result_array() AS $row){
$result[] = array (
'id' => $row['id'],
'nm' => $row['nm'],
'golcust' => $row['golcust'],
'golcustbi' => $row['golcustbi'],
'jnsbh' => $row['jnsbh']
);
}
$this->db->insert_batch('test3',$result);
How can I fix it?
i get error
Error Number: 37000
[Microsoft][ODBC SQL Server Driver][SQL Server]Error converting data type varchar to numeric.
SELECT * FROM test3 WHERE id IN(1,2,3,4)
Filename: D:/xampp/htdocs/sipdn/system/database/DB_driver.php
Line Number: 691
I think you are not seeing that when you do this:
$array[] = array('id' => $row->id);
You are assigning an array, inside another array, and the implode function is expecting an array of values, and not an array of array with values.
The answer is that you should do this
foreach ($sql->result() AS $row){
$array = array('id' => $row->id);
$implode = IMPLODE(',',$array);
}
Instead of this
foreach ($sql->result() AS $row){
$array[] = array('id' => $row->id);
$implode = IMPLODE(',',$array);
}
And the reason is that implode function firm is
string implode ( string $glue , array $strings )
Hope it helps!
try this, the simple code without implode and array
$sql = $this->db->query('select * from TEST');
$val = '';
foreach ($sql->result() AS $row){
$val .= $row->id.',';
}
// before rtrim $val is 1,2,3,
$val = rtrim($val,',');
// after rtrim $val is 1,2,3
$query = $this->db->query("SELECT * FROM TEST WHERE id IN('".$val."')");
// finally query will be "SELECT * FROM TEST WHERE id IN('1,2,3')"
may it can help you
You are setting an array inside an array. $array[] = means create a new key in $array and put everything after the equal sign into that key. So you don't have to create a new array.
It is simple as this $array[] = $row->id.
Then $array[0] would be the first id that is in the database and so on.
The problem solved I'm using query like bellow. Thanks all for response.
$sql = $this->db->query('select * from TEST');
foreach ($sql->result() AS $row){
$array[] = array('id' => $row->id);
}
$query = $db2->query("SELECT * FROM mCIF WHERE nocif IN ('".implode("','",$array)."')");
$result = array();
foreach($query->result_array() AS $row){
$result[] = array (
'id' => $row['id'],
'nm' => $row['nm'],
'golcust' => $row['golcust'],
'golcustbi' => $row['golcustbi'],
'jnsbh' => $row['jnsbh']
);
}
$this->db->insert_batch('test3',$result);

Make Associative array with three element in array

I want three element in associative array, so far am successful in getting two in the array.
$sql = "SELECT * FROM `notification_table` ";
$resultsd1 = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($resultsd1);
$associativeArray = array();
while ($row = mysqli_fetch_assoc($resultsd1))
{
$associativeArray[$row['name']] = $row['price'] ;
}
foreach($associativeArray as $k => $id){
echo $k."=>".$id .' ';
}
And am getting the response like this
name1=>24.725 name2=>24.265
Now i want to add another column in array as well and the name is column is notification_check .
Am not able to get how to add three columns in a single array. Any help will be appreciated.
I want the output like name1=>24.725=>yes_notification name2=>25.43=>no_notification
And when i print_r($row) is show this output Array ( [sno] => 1 [name] => name1 [price] => 23 [notification_check] => yes_notification)
You could shorten this and use mysqli_fetch_all to create an array of all of the data and then manipulate the array using array_column to create the index...
$result = mysqli_fetch_all($resultsd1, MYSQLI_ASSOC);
$associativeArray = array_column($result, null, 'name');

PHP SQL statement using REGEXP to fetch multiple values

How do I use REGEXP to fetch multiple data from the array $vall.
I referred a sample code from:
PHP sql statement where clause to multiple array values
Some of the sample data: CGCG-0025-0,CGCR-0003-0,CGRQ-0163-0
foreach ($list as $value) // this $list is from another array
{
$part = $value[3];
$vall[] = $value[3]; // $list1 is an empty array
}
$partnumber =[];
foreach($vall as $v)
{
$partnumber[] = "*.".$v.".*";
print_r(array_values($partnumber)); // these are some of the values Array ( [0] => *.CGCG-0025-0.* ) Array ( [0] => *.CGCG-0025-0.* [1] => *.CGCG-0025-0.* ) Array ( [0] => *.CGCG-0025-0.* [1] => *.CGCG-0025-0.* [2] => *.CGCR-0003-0.* )
}
foreach($partnumber as $x)
{
echo '<br>'.$partnumber; // shows 'Array' on each lines
}
$fsql="select * from Error where RptDatime = 201706091000 and partnumber REGEXP '".implode("|",$partnumber)."'";
//example 1 $fsql="select * from MPdError where RptDatime = 201706091000 and partnumber = ('CGRQ-0057-0') ";
//example 1 shows the correct data but i need multiple partnumber
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row)
{
$mac = $row['Machine'];
$id = $row['Id'];
echo '<br><br><br>ID:'.$id.'<br>Machine Number :'.$mac;
}
Though this may not be a good solution as it contains a huge security risk, I will still post it based on what is needed above.
REGEXP is not needed for data that are not complex in design.
$fsql = "select * from Error where RptDatime = 201706091000 and partnumber in ('" . implode("','", $vall) . "');"

add values into multidimensional array

I have a foreach loop that goes through a list of items. For each of these items, I have a while loop that grabs data out of a database.
$output = array();
//$reference is a multidimensional array has been passed to this page
where the element `color` contains the color I want.
foreach ($reference as $c) {
$color = $c['color'];
$query = "SELECT DISTINCT name FROM $table where colorPreference = $color";
$exquery = mysqli_query($con, $customerQuery);
while ($row = mysqli_fetch_array($exquery)) {
$person = $row['person'];
array_push($output[$color], $person);
}
}
So this loops through, the first time searching 'red', and finding 5 people in the fake table who like red. Next, 'blue', where it finds 1 person, and then 'green' where it finds 3.
If I look at the individual results, my first array has "red, blue, green" and my second array has these lists of names.... I just don't know how to add them into an array together.
I'm trying to build an array like this:
Array
(
[Red] => Array
(
[0] => John
[1] => Sally
[2] => Bob
...
)
[Blue] => Array
(
[0] => Luke
)
[Green] => Array
(
..etc...
)
I'm not using array_push correctly though - I'm getting an Warning: Illegal offset type error. What am I doing wrong?
It's been a while since I've worked with PHP, but I think you need to initialize each "color" array that you're going to push into. So...
$output = array();
//$reference is a multidimentional array has been passed to this page
where the element `color` contains the color I want.
foreach ($reference as $c) {
$color = $c['color'];
$query = "SELECT DISTINCT name FROM $table where colorPreference = $color";
$exquery = mysqli_query($con, $customerQuery);
while ($row = mysqli_fetch_array($exquery)) {
$person = $row['person'];
if (!array_key_exists($color, $output)) {
$output[$color] = array();
}
array_push($output[$color], $person);
}
}
Try changing:
array_push($output[$color], $person);
Into:
$output[$color][] = $person;
From the manual on array_push:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.

How can I create an array with key value pairs?

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'];
}
}

Categories