I'm hoping somebody knows what is going on with this. I've never seen anything like this before. I'm trying to re-key the results from an indexed array to a keyed array using the value of 'code' in the results as it is a unique key. This happens in both PHP 5.4.16 and PHP 7.0.10
The following code produces very strange output:
$stmt = $conn->prepare( $sql );
$stmt->execute( $params );
$key = 'code';
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print "Value of $key is '{$row['code']}'\n";
$rows[ ($row['code']) ] = $row;
}
This produces the following output:
'alue of code is '1286
] => Array
(
[code] => 1286
[EmployeeID] =>
[Name] =>
)
Notice how the value of $row['code'] is printed to STDOUT after the single quotes and the V in Value is cut off. This causes my re-keyed array ($rows) to have no key value. I've re-keyed arrays from database results thousands of times before and never had a problem until I started using PDO. Anybody have any ideas?
I simplified the quoting by issuing:
print "Value of $key is '"."{$row[$key]}"."'\n";
which resulted in:
'alue of EmployeeCode is '1286
I am mystified why it's cutting off the 'V' in Value.
I can get similar output without using any database calls this way:
$row = [
'code' => "1286\r",
'EmployeeID' => '',
'Name' => ''
];
print "Value of $key is '{$row['code']}'\n";
$rows[ ($row['code']) ] = $row;
print_r($rows);
Output:
'alue of is '1286
Array
(
] => Array
(
[code] => 1286
[EmployeeID] =>
[Name] =>
)
)
The \r character causes the output cursor to jump to the start of the line, so the ' that's overwriting your 'V' character is actually the second single-quote you're printing.
Likewise, in the strange output of print_r(), the \r is jumping the output cursor to the start of the line, so the ] => Array is overwriting what came before it, which was [1286\r.
I suspect the data in your database contains literal \r characters.
Related
I have a problem with the array PHP function, below is my first sample code:
$country = array(
"Holland" => "David",
"England" => "Holly"
);
print_r ($country);
This is the result Array ( [Holland] => David [England] => Holly )
I want to ask, is possible to make the array data become variables? For second example like below the sample code, I want to store the data in the variable $data the put inside the array.:
$data = '"Holland" => "David","England" => "Holly"';
$country = array($data);
print_r ($country);
But this result is shown me like this: Array ( [0] => "Holland" => "David","England" => "Holly" )
May I know these two conditions why the results are not the same? Actually, I want the two conditions can get the same results, which is Array ( [Holland] => David [England] => Holly ).
Hope someone can guide me on how to solve this problem. Thanks.
You can use the following Code.
<?php
$country = array(
"Holland" => "David",
"England" => "Holly"
);
foreach ($country as $index => $value)
{
$$index = $value;
}
?>
Now, Holland & England are two variables. You can use them using $Holland etc.
A syntax such as $$variable is called Variable Variable. Actually The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So there is this thing called
Destructuring
You can do it something like ["Holland" => $eolland, "England" => $england] = $country;
And now you have your array elements inside the variables.
Go read the article above if you want more information about this because it gets really useful (especially in unit tests usind data provders from my experience).
If you want to extract elements from an associative array such that the keys become variable names and values become the value of that variable you can use extract
extract($country);
To check what changed you can do
print_r(get_defined_vars());
Explanation on why the below does not work
$data = '"Holland" => "David","England" => "Holly"';
When you enclose the above in single quotes ' php would recognise it as a string. And php will parse a string as a string and not as an array.
Do note it is not enough to create a string with the same syntax as the code and expect php to parse it as code. The codes will work if you do this
$data = ["Holland" => "David","England" => "Holly"];
However, now $data itself is an array.
A simple copy of an array can be made by using
$data = $country;
I have this PHP array:
$this->user_list = array( 0 => 'Not paid',1 => 'Not paid', 2 => 'Not paid', 7 => 'Waiting, 15 => 'Waiting', 10 => 'Cancelled' );
How can I simplify this array as the id numbers are different, but some of them have same status?
I tried it like this:
$this->user_list = array( [0,1,2 => 'Not paid'],[7,15 => 'Waiting'],10 => 'Cancelled' );
but it doesn't work as expected.
Basically I want to achieve this:
echo $this->user_list[15] should give me Waiting, echo $this->user_list[10] should give me Cancelled, etc. So this is working in my first array very well, I am just thinking about grouping duplicate names there.
As mentioned by other contributors, there is no native support in the PHP grammar for your intended use case. As clearly stated in the PHP: Arrays documentation:
An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments.
So basically each element in an array is a key => value pair, which means you cannot associate multiple keys to a single element.
This also explains why your first tentative didn't work:
$this->user_list = array( [0,1,2 => 'Not paid'],[7,15 => 'Waiting'],10 => 'Cancelled' );
If you don't specify a key for an element, PHP uses a progressive index (0, 1, ...). So basically in the example above, the first zero is not actually a key, but a value, and PHP binds it to the key = 0. Maybe it could be easier for you to understand how it works if you print a var_dump or print_r of $this->user_list. You would get something similar to the following structure (NOTE: I have simplified the structure to make it more clear):
[
0 => [
0 => 0
1 => 1
2 => "Not paid"
],
1 => [
0 => 7,
15 => "Waiting"
],
10 => "Cancelled"
]
So how do we resolve this problem? Well... actually there is no need to contort the structure by swapping keys with values as other contributors seem to suggest. Changing the structure might simplify your "data entry" work but might also create big issues in other parts of the program because who knows, maybe accessing the invoice data by "ID" is simply more efficient than by "status" ... or something.
Since PHP does not provide such a feature out of the box, I believe a better solution would be to develop our own function; a good starting point could be the one in the example below.
function explode_array($config, $sep = ',') {
$res = [];
foreach($config as $configKey => $value) {
// split key values
$keys = explode($sep, $configKey);
foreach($keys as $key) {
$res[$key] = $value;
}
}
return $res;
}
$config = [
'0,1,2' => 'Not paid',
'7,15' => 'Waiting',
'10' => 'Cancelled'
];
$myArr = explode_array($config);
print_r($myArr);
The idea is quite simple: since we cannot use an array as key we leverage the next best data type, that is a CSV string. Please note there is no error handling in the above code, so the first thing you may want to do is adding some validation code to the explode_array (or however you wish to name it) function.
you should use like this. if id number is invoice id or something else and other value is there status about it.
$arr = array(
'Not paid' => [0,1,2] ,
'Waiting' => [5,6],
'Cancelled' =>[8]
);
foreach($arr as $key => $val){
foreach($val as $keys => $vals){
echo "invoiceid ".$vals ." status ".$key;
echo"<br>";
}
}
// for only one status you can use like this
foreach($arr['Not paid'] as $key => $val){
echo $val;
echo"<br>";
}
just try to run this and check output.
PHP has no built-in function or structure for handling cases like this. I'd use a simple array value-cloning function to map your duplicates. Simply have one instance of each status, then map the aliases, and then run a function that clones them in. As follows:
// Status list:
$ulist = [ 0 => 'Not paid', 7 => 'Waiting', 10 => 'Cancelled' ];
// Alternative IDs list, mapped to above source IDs:
$aliases = [ 0 => [1,2], 7 => [15] ];
// Function to clone array values:
function clone_values(array &$arr, array $aliases)
{
foreach($aliases as $src => $tgts) {
foreach($tgts as $tgt) {
$arr[$tgt] = $arr[$src];
}
}
ksort($arr); // If the order matters
}
// Let's clone:
clone_values($ulist, $aliases);
This results in the following array:
array(6) {
[0] · string(8) "Not paid"
[1] · string(8) "Not paid"
[2] · string(8) "Not paid"
[7] · string(7) "Waiting"
[10] · string(9) "Cancelled"
[15] · string(7) "Waiting"
}
....which can be accessed as you expect, here $ulist[2] => Not paid, etc. If the use case is as simple as illustrated in the OP, I'd personally just spell it out as is. There's no dramatic complexity to it. However, if you have dozens of aliases, mapping and cloning begins to make sense.
As said in the comments, you can't have multiple keys with one value. The best way is to use the keyword => [ number, number, number...] construction.
//set a result array
$result = [];
//loop the original array
foreach ( $this->user_list as $number => $keyword ){
//if the keyword doesn't exist in the result, create one
if(!isset ( $result [ $keyword ] ) ) $result[ $keyword ] = [];
//add the number to the keyword-array
$result[ $keyword ] [] = $number;
}
I have an array which I create. When reading the array with print_r it is not returning with the correct data inputted! I am missing specific sectionsn such as < & > brackets with its headings.
How can i preserve these?
Code:
$params = array(
"Parm1" => "test",
"Parm2" => "hi",
"Parm3" => GUID(),
"Parm4" => "lol",
"Parm5" => "
<R>
<R1>the</R1>
<R2>dog</R2>
<R3>is</R3>
<R15>happy</R15>
<R20>today</R20>
</R>
");
Basically the only data that is jumbled up is the Parm5 section. I want everything inside to return exactly as it is! EG: Reading as is i only receive Array ( [Parm1] => test [Parm2] => hi [Parm3] => B18BE727-8F79-4D4A-80EA-3974B1429F78 [Parm4] => lol [Parm5] => the dog is happy today ) from print_r
I want to return:
Array ( [Parm1] => test [Parm2] => hi [Parm3] => B18BE727-8F79-4D4A-80EA-3974B1429F78 [Parm4] => lol [Parm5] => <R><R1>the</R1> <R2>dog</R2> <R3>is</R3> <R15>happy</R15> <R20>today</R20></R> )
escape param5 with htmlspecialchars('<R> ..... </R>'). Your browser currently sees it as html tags and parses it.
Use htmlspecialchars on the return value of print_r:
echo "<pre>";
echo htmlspecialchars(print_r($params, true));
echo "</pre>";
Hi I am currently having an error that says illegal string offset and i already searh here I just know that you get that warning if you are treating a string as if it is an array but I am certain that I am using it as an array can anybody help me thanks
$data2 = array('EquipmentName' => $this->input->post('txt_equipb'),
'EquipmentType' => $this->input->post('txt_equiptype'),
'RequirementID' => $id2);
foreach($data2 as $d) {
$data2s = array('EquipmentName' => $d['EquipmentName'],
'EquipmentType' => $d['EquipmentType'],
'RequirementID' => $d['RequirementID']);
}
You've misunderstand the meaning of foreach.(sigh)
Suggestions Provided:
just var_dump($d); before assignment of $data2s, and you'll know the result.
In the foreach, as you could see, each $d is only the value part of $data2, which means in every assignment of $data2s, there's no key as 'EquipmentName', only a simple string.
If you're just gonna loop once to set array values to a variable, you may just simply do it this way without using a foreach loop.
$data2 = array('EquipmentName' => $this->input->post('txt_equipb'),
'EquipmentType' => $this->input->post('txt_equiptype'),
'RequirementID' => $id2);
$data2s = $data2;
print_r( $data2s ); // check if has values
New to programming so please explain as simply as possible. I have an array as $inputs. That array has rows as row0, row1 and on. Each row has key value pairs such as name='shay', age='23' and a few other things. I need to put those values in a database, but I can't figure out how to get to them and the examples I find go right over my head. I have made a loop with
for ($i = 0, $nums = count($inputs); $i < $nums; $i++)
But once inside of that loop I am lost as to what comes next. Please help.
The array looks as follows:
$inputs =array (
'row' => array (
0 => array ( 'id' => '2869', 'name' => 'shay', 'age' => '23',),
1 => array ( 'id' => '2868', 'name' => 'Tim', 'age' => '30',),
What I need to do is go through and do an insert with $name, $age etc. So I created the for loop, but I have no idea what to do inside of it to get the values of name and age etc for each row. I know how to insert them, it's just getting the values out of the array.
When I use
foreach ($inputs as $key => $row)
I can then do
dd($row['0']);
And return the contents of a row that I would then like to put in my query. I just don't really understand how to go from the dd() to actually accessing the values for each rows in a way that I could insert them.
You can loop over that data like this:
foreach($inputs as $key => $row) {
echo "row $key:\n";
foreach ($row as $person) {
echo " - " . $person['name'], " is ", $person['age'], " old.\n";
}
}
See it run on eval.in
Output based on the input you provided:
row row:
- shay is 23 old.
- Tim is 30 old.