Dynamic Array Overwriting - php

I'm new to array and I have a decrypt function and sql query. Process is I query in the database and return the $get in an array like so:
array (size=1)
0 =>
array (size=3)
'Username' => string 'joenefloresca' (length=13)
'MiddleName' => string 'Estero' (length=6)
'Email' => string 'joenefloresca#gmail.com' (length=23)
What I want is to use my decrpyt function (data is encrypted, above is just an example). When I decrypt
it I want it to overwrite $get array with the decrypted values. I can do it this way,
foreach( $get as $key => $result )
{
$get[$key]['Username'] = $decr->decrypt($result['Username']);
$get[$key]['MiddleName'] = $decr->decrypt($result['MiddleName']);
$get[$key]['Email'] = $decr->decrypt($result['Email']);
}
But I can do that if my Fields like Username,MiddleName,Email is fixed in the sql query, what if
it is dynamic? Fields in the query is defined by the user, ex. What if Username is the only field? or Username and Email only? How can I overwrite the array with the decrypted one with the selected Field only?
Thanks.

Just nest another loop inside if you do not want to explicitly set the index you want:
foreach($get as $key => $result) {
foreach($result as $k => $val) { // will loop for each piece/copy of `$result`
$get[$key][$k] = $decr->decrypt($val);
}
}

Related

String with Multiple delimiters- MySQL Insert row by row

I am inserting string with multiple delimiters and split it using explode function to mysql database table but i failed in building proper logic.
I tried with single delimiter i-e , and successfully insert that record.
Now i want to split string with | and ,.
I used for row separation and | for value seperation.
i-e
$var = "Facebook|http://facebook.com/123|12312|12 to 13,Twitter|http://twitter.com/231|12321|12 to 13";
$cat="2,3";
$i=0;
$arrayOfCategories = explode(",", $cat);
foreach ($arrayOfCategories as $categories) {
$datas[$i]['UserID'] = 2;
$datas[$i]['CatID'] = $categories;
$i++;
}
var_dump($datas);
Format showed using var_dump is the format which i want to insert using insert_batch of codeigniter.
This is the expected output
array (size=2)
0 => array (size=2)
'SocialName' => string 'Facebook'
'URL' => string 'facebook.com/123'
1 => array (size=2)
'SocialName' => string 'Twitter'
'URL' => string 'twitter.com/231'
$array = array();
$string = "Facebook|http://facebook.com/123|12312|12 to 13,Twitter|http://twitter.com/231|12321|12 to 13";
$rows = explode(',', $string);
foreach ($rows as $row) {
$values = explode('|', $row);
$array[] = array('SocialName' => $values[0], 'URL' => $values[1]);
}
var_dump($array);
Create an array $array to store the final result in.
Now, split the input string $string on , using explode, this gives you the "rows".
Go through all the rows (foreach), and split each row on the | (explode), this gives you the "values".
The first value $values[0] is the "SocialName", and the second value $values[1] is the "URL", so add those to a new array, and add that new array to the final result array $array.

2-dimensional array to 1-dimensional array convertion

With my code:
$sql = "SELECT number.phone_number FROM number, ordered_number WHERE ordered_number.number_id=number.id AND ordered_number.order_id=$id";
$connection = \Yii::$app->getDb();
$command = $connection->createCommand($sql);
$numery = $command->queryAll();
I get array that looks like this:
array (size=3)
0 =>
array (size=1)
'phone_number' => string '546732354' (length=9)
1 =>
array (size=1)
'phone_number' => string '565345456' (length=9)
2 =>
array (size=1)
'phone_number' => string '456557546' (length=9)
I want to get simple array, where the first element is just the number (here - the string), without name 'phone_number' and additional 1-element arrays inside the main array. When I try to do foreach on this array, it tells me that I use "Illegal offset type". I found that it means I'm using object, instead of an array, but that's an array, not an object and I have no idea what to do.
Even simplier (but for php5.5 and php7):
$numery = array_column(
$command->queryAll(),
'phone_number'
);
Use below loop to get desired result
$numery = $command->queryAll();
$number_arr = array();
foreach($numery as $number)
{
array_push($number_arr,$number['phone_number']);
}
print_r($number_arr);

Converting array to individual variables

I am using simplehtmldom to parse a webpage and extract a data and then put it in a mysql database. I successfully extracted the data and put it in array but now the problem i am facing is how to convert this array to variable so that I may use it in my database query to insert the record in the specific fields. I want to convert array to individual variables
here is the code
<?php
include("simple_html_dom.php");
$html = file_get_html('abc.html');
$sched = array();
foreach ( $html->find('tr[class=highlight-darkgrey]') as $event ) {
$item['title'] = trim($event->find('td', 1)->plaintext);
$sched[] = $item;
}
var_dump($sched);
?>
and the output is
array (size=6)
0 =>
array (size=1)
'title' => string 'Network admin, field engineer, engineering analyst, sales executive, PA to HR director Required by Telecommunication Company' (length=124)
1 =>
array (size=1)
'title' => string 'Karachi, Hydrabad, Lahore, Rawalpindi, Peshawar, Multan, Faisalabad' (length=67)
2 =>
array (size=1)
'title' => string '5 - 6 Years' (length=11)
3 =>
array (size=1)
'title' => string 'Knowledge of Field' (length=18)
4 =>
array (size=1)
'title' => string '' (length=0)
5 =>
array (size=1)
'title' => string '- Salary and incentives are not full and final. Can be discussed on final interview.
Can please somebody help me in achieving it. Thanks in advance
Well, if this needs to go in specific fields then you can do something like this:
INSERT INTO table_name (column1, column2, column3,...)
VALUES ($sched[0]['title'], $sched[1]['title'], $sched[2]['title'],...);
Php has a function for getting individual variables, extract() http://php.net/manual/en/function.extract.php
However I don't know why you would do that instead of just using a loop to go though your array.
You mean somethign like
foreach($sched as $item) {
$title = $item['title'];
insert_into_db($title);
}
?
Why do you want to move data from one perfectly good location i.e. the array into a scalar variable.
Double your memory usage for no actual reason.
I assume you are going to want to store the title's in a table
So you can :
foreach ( $sched as $one_sched ) {
// do your database update using $one_sched['title'] as the data identifier.
}
Why not use the array values directly? Also to me it makes no sense to build a subarray where every field is called title.
$sched = array();
foreach ( $html->find('tr[class=highlight-darkgrey]') as $event ) {
$sched[] = trim($event->find('td', 1)->plaintext);
}
Then access the values like:
$value0 = $sched[0];
$value1 = $sched[1];
// PDO example
$sth = $dbh->prepare(
'INSERT INTO table VALUES (?, ?, ...)'
);
$sth->execute(array($sched[0], $sched[1], ...));
// or if array count is right
$sth->execute($sched);

PHP Get Values Out of Checkbox Array

I am trying to figure out how to get values out of a checkbox array. The checkbox array var_dump looks like the following:
array (size=50)
0 => string '104702|0' (length=8)
1 => string '52278|1' (length=7)
2 => string '69891|1' (length=7)
3 => string '153335|1' (length=8)
4 => string '131140|1' (length=8)
. . .
I am sending two different IDs in each array value, separated by a pipe and would like to assign each part to different variables, $variable1, $variable2, so I can use them in a database query. How can I do this?
Thanks for your help.
EDIT: Even though I've accepted an answer below, here is the complete answer I was looking for:
To get the values out of the above array so I can use them in my database query, I did the following to first break them apart:
foreach ($input as $key => $value) {
$this->combinedIds[] = explode('|', $value);
}
Then, to get the values into separate variables, I did the following:
foreach ($this->combinedIds as $key => $value) {
$firstId = $value[0];
$secondId = $value[1]
// do something with the values ...
}
Use foreach loop on the array and explode each value with pipe symbol. Something like this :
foreach ($arr as $val)
{
$newData = explode("|", $val);
}
A different variant (using an anonymous function) would be something like:
$values = array_map(function ($input) { $tmp = explode("|", $input); return ["id1" => current($tmp), "id2" => end($tmp)]; }, $array);.
This is written for PHP 5.4+. If you need a version compatible with PHP 5.3 and downwards, just substitute the brackets with its corresponding array(...) equivalent.

Create array from mysql query. Column2 as key Column 1 as value

I have a table that contains
column 1 = state column 2 = link
Alabama auburn.alabama.com
Alabama bham.alabama.com
Alabama dothan.alabama.com
I need to grab from my database table and put into an array that i can array_walk() through. they need to be accessed like this array.
$arraytable = array(
"auburn.alabama.com"=>"Alabama",
"bham.alabama.com"=>"Alabama",
"dothan.alabama.com"=>"Alabama",
);
I have tried everything but not sure how make this work using php to print the array like such. Any help is greatly appreciated.
Note Your question title is inconsistent with your example. In the title you ask for column 1 as the key, but your example uses column 2 as the key. I've used column 2 here...
It isn't clear what MySQL API you are using to fetch, but whichever it is, use the associative fetch method and create new array keys using the pattern $arraytable[$newkey] = $newvalue. This example would be in object-oriented MySQLi:
$arraytable = array();
while($row = $result->fetch_assoc()) {
// Create a new array key with the 'link' and assign the 'state'
$arraytable[$row['link']] = $row['state'];
}
You can use array_column for this, since PHP5.5 (http://php.net/array_column)
Description
array array_column ( array $array , mixed $column_key [, mixed $index_key = null ] )
array_column() returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.
For PHP < 5.5:
https://github.com/ramsey/array_column/blob/master/src/array_column.php
To implement AcidReign's suggestion, here is the snippet:
Code: (Demo)
$resultset = [
['state' => 'Alabama', 'link' => 'auburn.alabama.com'],
['state' => 'Alabama', 'link' => 'bham.alabama.com'],
['state' => 'Alabama', 'link' => 'dothan.alabama.com']
];
var_export(array_column($resultset, 'state', 'link'));
// ^^^^-- use this column's data for keys
// ^^^^^-- use this column's data for values
Output:
array (
'auburn.alabama.com' => 'Alabama',
'bham.alabama.com' => 'Alabama',
'dothan.alabama.com' => 'Alabama',
)
However, array_column() won't directly work on a result set object, but a foreach() can immediately access the data set using array syntax without any fetching function calls.
Body-less foreach: (Demo)
$result = [];
foreach ($mysqli->query('SELECT * FROM my_table') as ['link' => $link, 'state' => $result[$link]]);
var_export($result);
Or a foreach with a body: (Demo)
$result = [];
foreach ($mysqli->query('SELECT * FROM my_table') as $row) {
$result[$row['link']] = $row['state'];
}
var_export($result);
All of the above snippets return:
array (
'auburn.alabama.com' => 'Alabama',
'bham.alabama.com' => 'Alabama',
'dothan.alabama.com' => 'Alabama',
)

Categories