PHP replace characters in array - php

I'm trying to replace quotes and others characters from a mysql result array, using strtr() function. But i got Warning: strtr() expects parameter 1 to be string, array given and null values.
Heres my code:
while($rows = mysqli_fetch_assoc($list)){
$string_filter = array(';'=>'','['=>'',']'=>'','{'=>'','}'=>'','"'=>'',"'"=>'');
$data[$rows['id']] = strtr($rows,$string_filter);
}
$data is an array that i want to remove/trim the characters specified in $string_filter array. Heres the content sample from $data:
Array ( [1] => Array ( [id] => 1 [user_id] => 204554 [name] => Rich [group] => PL [ai] => BA [image] => 204554-35849.jpg ) [2] => Array ( [id] => 2 [user_id] => 124534 [name] => James [group] => SS [ai] => IT [image] => 123141-12312.jpg )...

Quick Question, are you sure these characters actually exist in your data? Because the characters you are trying to remove are the ones php will automatically append to an array when that array is viewed via the print_r function. To be precise this statement
print_r(array('key' => 'value'));
will output
Array([key] => value)
even tough there is no actual [ or ] present in the arrays data itself.
In any case this code snippet will clean the keys and values of your array:
$string_filter = array(';'=>'','['=>'',']'=>'','{'=>'','}'=>'','"'=>'',"'"=>'');
while($rows = mysqli_fetch_assoc($list)){
$cleanedrow = [];
foreach($rows as $key => $value) {
$cleanedrow[strtr($key, $string_filter)] = strtr($value, $string_filter);
}
$data[$rows['id']] = $cleanedrow;
}

Related

Replace the array values with html image tag in php

I have here an array below:
<?php
print_r( $result );
?>
If I am going to execute the code above, it resulted below:
Array
(
[0] => Array
(
[id] => 1
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_2.jpg
[work_description] => test
[date_added] => 2017-08-03 02:12:38
)
[1] => Array
(
[id] => 2
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_4.jpg
[work_description] => test
[date_added] => 2017-08-03 02:13:04
)
[2] => Array
(
[id] => 3
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_2.jpg
[work_description] => test
[date_added] => 2017-08-03 02:46:28
)
[3] => Array
(
[id] => 4
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_2.jpg
[work_description] => sdfsdf
[date_added] => 2017-08-03 02:46:34
)
)
Now, from the $result array I wanted to change the values of all image_url
programmatically using php into an image in html.
example:
http://localhost/dir/img_2.jpg will become
<img src="http://localhost/dir/img_2.jpg"/>
Those values must be changed if I am going to execute the code.
Does anybody know?
You can put it in a foreach and modify only the part what you want:
foreach($result as $key => $value) {
$result[$key]['image_url'] = '<img src="'.$value['image_url'].'"/>';
}
print_r($result);
You can use a compact syntax and modify the subarray elements by reference:
Code: (Demo)
foreach ($result as &$subarray) { // & means modify by reference, so you are overwriting the input array, not traversing a copy.
$subarray['image_url'] = "<img src=\"{$subarray['image_url']}\"/>";
}
var_export($result);
There is no need to declare $key because the foreach is traversing the actual input array, not a copy of the input array. The image_urls are simply overwritten with each iteration.

Setting an array item's value as the parent array's key (PHP) [duplicate]

This question already has answers here:
Generate an associative array from an array of rows using one column as keys and another column as values
(3 answers)
Closed 7 months ago.
I have an array of array that looks like this:
Array
(
[0] => Array
(
[id] => I100
[name] => Mary
[gender] => F
)
[1] => Array
(
[id] => I101
[name] => John
[gender] => M
)
[2] => Array
(
[id] => I245
[name] => Sarah
[gender] => F
)
)
I want to set the key of the parent array with the value of id, so the result array looks like this:
Array
(
[I100] => Array
(
[id] => I100
[name] => Mary
[gender] => F
)
[I101] => Array
(
[id] => I101
[name] => John
[gender] => M
)
[I245] => Array
(
[id] => I245
[name] => Sarah
[gender] => F
)
)
If possible I'd like to avoid using an additional loop to go through the array and creating a new array to store each item with the proper key, as the array can have thousands of items.
Thanks in advanced!
Despite your caveat, a loop is the obvious solution:
$newArray = [];
foreach($oldArray as $item)
$newArray[$item['id']] = $item;
If the problem you have is not specifically with a loop, but rather creating a copy of the array is causes excessive memory consumption, then you can edit the array in place, with a for loop:
for($i=0; $i<count($oldArray); $i++){
$oldArray[$oldArray[$i]['id']] = $oldArray[$i];
unset($oldArray[$i]);
}
Note this works because the id elements are alphanumeric strings, if they where simple integars then the above code could overwrite sections.
The only other solution is to build the correct array in the 1st place, in a similar manner.
For example, using PDO::fetch instead of PDO::fetchAll:
//$newArray = $sth->fetchAll(PDO::FETCH_ASSOC);
$newArray = [];
while($row = $sth->fetch(PDO::FETCH_ASSOC))
$newArray[$row['id']] = $row;
You can't overwrite keys while iterating through an array "on the fly". So here is solution with array_map which produces an array with needed structure:
// assuming $arr is your initial array
$result = [];
array_map(function($a) use (&$result){
$result[$a['id']] = $a;
}, $arr);
// $result contains the needed array
You can add needed key during creation of this array.

Explode Array and store in db

I'm having a problem exploding an array
Here's my code
$arr1 = array();
$i=1;
foreach ($out1 as $value2){
$arr1[][$i]= array_merge((array)$value2,(array)$detail);
$i++;
}
and this is the output
Array(
[0] => Array(
[id] => 1234
[name] => Rick Roll
[dept] => IT)
[1] => Array(
[id] => 1234
[name] => Dave Roll
[dept] => IT)
)
but when i try to explode the array it gives me error message
Warning: explode() expects parameter 2 to be string, array given
here's the code
$data = explode(","$array)
$q = "INSERT INTO ".TBL_ARE_ENTRY." VALUES(null,'$id[1]','$name[2]','$dept[3]')";
You do not need to use explode. i think this is what you want:
$q = "INSERT INTO ".TBL_ARE_ENTRY."
VALUES(null,''$array[0][0]','$array[0][1]',''$array[0][2]')";

Handling PHP Array post values and merging - PHP Arrays

I know this won't take much time for experts here. But still please help me out
My Array output is like this
Array ( [0] => 1 [1] => 37 [2] => 1035 ) 1
Array ( [0] => 1 [1] => 37 [2] => 1035 ) mystatusmessage1
Array ( [0] => 4 [1] => 37 [2] => 2925 ) 2
Array ( [0] => 4 [1] => 37 [2] => 2925 ) mystatusmessage2
What I would like to get it is in a single string value like this so that I can insert into database.
1,37,1035,1,mystatusmessage1
4,37,2925,2,mystatusmessage2
How can I achieve that. I'm trying to do with foreach but still I'm not able to do it.
Thanks,
Kimz
use implode function to make string from array for example
if you have array like Array('a','b','c');
implode(',',array('a','b','c') )
will return a,b,c as string
here first argument is your glue by which you want to join string
Here you go.
// Original array
$array = array(0 => 1, 1 => 37, 2 => 1035);
// $_POST array
$_POST = array(1,'mystatusmessage1');
// Jump to the end of array
end($array);
// Merge the post with original array
$newArr = array_merge($array,$_POST);
// Impode
echo implode(",",$newArr);
Repeat with other array.

PDO fetchAll() primary key as array group key

I want to store the contents of a specific database into an array, grouped by their primary keys. (Instead of the useless way PDO fetchAll() organises them).
My current code:
$DownloadsPDO = $database->dbh->prepare("SELECT * FROM `downloads`");
$DownloadsArray = $DownloadsPDO->execute();
$DownloadsArray = $DownloadsPDO->fetchAll();
Which then outputs:
Array ( [0] => Array ( [id] => 0 [0] => 0 [path] => /xx-xx/testfile.zip [1] => /xx-xx/testfile.zip [name] => Test Script [2] => Test Script [status] => 1 [3] => 1 ) [1] => Array ( [id] => 1 [0] => 1 [path] => /xx-xx/test--file.zip [1] => /xxxx/testfile.zip [name] => New Script-UPDATE [2] => New Script-UPDATE [status] => 1 [3] => 1 ) )
I was considering to use PDO::FETCH_PAIR, however I will be very soon expanding the amount of data I want to be able to use on this script. This works currently, but when I start to expand the amount of downloads and more clients come into play, obviously the way the data is grouped causes an issue.
Is it possible for me to group each array by their primary key (which is id)?
You can just use
$results = array_map('reset', $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC))
PDO::FETCH_GROUP|PDO::FETCH_ASSOC returns an array of arrays. The first column is used as the key, and then within key is an array of all the results for that key. However, in our scenario each key will only contain 1 row. reset() returns the first element in array, thus eliminating 1 level of nesting.
This should yield what you are looking for :
$results = $pdos->fetchAll(\PDO::FETCH_UNIQUE|\PDO::FETCH_ASSOC);
I decided to just loop through the results with fetch() and enter them into an array as I go along, this is the code I have used and it works just fine:
$DownloadsPDO = $database->dbh->query("SELECT * FROM `downloads`");
$Array = array();
while ($d = $DownloadsPDO->fetch()) {
$Array[$d['id']]["id"] = $d['id'];
$Array[$d['id']]["name"] = $d['name'];
$Array[$d['id']]["path"] = $d['path'];
}
// Outputs
Array ( [1] => Array ( [id] => 1 [name] => Test Script [path] => /xxxx/testfile.zip ) [2] => Array ( [id] => 2 [name] => New Script-UPDATE [path] => /xxxx/testfile.zip ) )
Which uses the primary key (being id) as the name for the array key, and then adds the data into it.
Thought I would add this as the answer as this solved it, thanks to the guys that helped out and I hope this is helpful to anyone else hoping to achieve the same thing.
I'd like to point out the only solution that works for me:
fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_UNIQUE|\PDO::FETCH_ASSOC);
Beware that this will strip the first column from the resultset. So the query must be:
SELECT id_keyname AS arrkey, id_keyname, .... FROM ...
I'm still suggesting you to loop using fetch() method. Otherwise, you can use array_reduce() to iterate over the array. A sample on codepad is here.
The code(in human readable form) will be:
$myFinalArray = array_reduce($myInputArray, function($returnArray, $temp) {
$temp2 = $temp['id'];
unset($temp['id']);
$returnArray[$temp2] = $temp;
return $returnArray;
}
);
So, my question is; is it possible for me to group each array by their
primary key (which is id)
Off course, you have 2 options here: Either to change the query or parse a result-set.
So, I'm sure you don't want to change query itself, so I'd go with parsing result-set.
Note:
You should use prepared SQL statements when they make sense. If you want to bind some parameters then its OKAY. But in this case, you only want get get result-set, so prepare() and fetch() will be kinda overdo.
So, you have:
Array ( [0] => Array ( [id] => 0 [0] => 0 [path] => /xx-xx/testfile.zip [1] => /xx-xx/testfile.zip [name] => Test Script [2] => Test Script [status] => 1 [3] => 1 ) [1] => Array ( [id] => 1 [0] => 1 [path] => /xx-xx/test--file.zip [1] => /xxxx/testfile.zip [name] => New Script-UPDATE [2] => New Script-UPDATE [status] => 1 [3] => 1 ) )
And you want:
Array( [id] => Array('bar' => 'foo') ....)
Well, you can do something like this:
$stmt = $database->dbh->query("SELECT * FROM `downloads`");
$result = array();
foreach($stmt as $array){
$result[$array['id']] = $array;
}
print_r($result); // Outputs: Array(Array('id' => Array(...)))

Categories