I have an array in php, with print_r it looks like this
Array (
[0] => Array ( [0] => 2 [1] => 3 [2] => 3 [3] => 1 [4] => 1 [5] => 4 [6] => 1 )
[1] => Array ( [0] => 1 [1] => 2 [2] => 2 [3] => 1 [4] => 1 [5] => 1 [6] => 1 )
)
when I do json_encode($mydata) it looks like this
[["2","3","3","1","1","4","1"],["1","2","2","1","1","1","1"]]
but I need this without the quotes, as the next processing simply needs a dataset like this:
var dataset = [ 5, 10, 15, 20, 25 ];
the dataset was never intended to use json standards, I simply need to get my array formatted correctly.
so the question is either "how do I remove quotes from json" which is simply nonstandard invalid json and won't get me the responses I'd need
OR
"how do I format this php array to be like the dataset".
it either involves a different kind of print function in php, or it involves some forloop regex in javascript
You need to use the JSON_NUMERIC_CHECK flag, this will force all numeric strings to be converted to numbers.
Like so:
json_encode($array,JSON_NUMERIC_CHECK);
Please note that this flag is only available from PHP version 5.3.3
Ehhh you could try this:
$d = array();
foreach($myData as $data) {
$d[] = "[" . implode(",", $data) . "]";
}
echo "[" . implode(",", $d) . "]";
Demo: http://codepad.org/nTveAGWm
Although echoing out json_encode($myData); worked as well: http://codepad.org/KTfQHz6s
The reason json_encode is putting quotes is because the data is a string.
Try this example to view the difference:
$arr = array(array(4,5,6), array(8,10, "11"));
print_r($arr);
echo "<br>";
echo json_encode($arr);
You can try to use intval to parse it as int before json_encoding
you could try this
$c = array(1,2,3);
echo "Non-associative array output: ", json_encode($c), "\n";
return this:
Non-associative array output: [1,2,3]
using your example string u can do smth like this
$arr = json_decode('[["2","3","3","1","1","4","1"],["1","2","2","1","1","1","1"]]');
foreach ($arr as &$val)
foreach ($val as &$item)
$item = (int)$item;
var_dump(json_encode($arr));
finally i get
string(33) "[[2,3,3,1,1,4,1],[1,2,2,1,1,1,1]]"
Related
I am just trying to create PHP variables dynamically. below is the code I have tried.
if($BrickTerritorys)
{
foreach($BrickTerritorys as $index=>$BrickTerritory)
{
${"$T.$index"}= $BrickTerritory->TerritoryID;
${"'Weightage'.$index"} = $BrickTerritory->Weightage;
}
echo $T1."-".$T2."--".$Weightage1."---".$Weightage2; exit;
}
while
$BrickTerritorys is
[1] => stdClass Object
(
[id] => 119
[TerritoryID] => HYD-2-CMD
[BrickCode] => 16
[BrickName] => BUHURO
[Weightage] => 40.00
[BPCode] => bp00066
[GroupCode] => CMD
)
[2] => stdClass Object
(
[id] => 36330
[TerritoryID] => HYD-1-CMD
[BrickCode] => 16
[BrickName] => BUHURO
[Weightage] => 60.00
[BPCode] => bp00066
[GroupCode] => CMD
)
When I print in the last, nothing gets printed. Any help is much appreciated, please.
Thanks in advance
${"T$index"} as well as ${"Weightage$index"}
you don't need the dot,or you can use ${'T' . $index}. look at the dot. it's not addition operation while it in "". following this code:
if($BrickTerritorys)
{
foreach($BrickTerritorys as $index=>$BrickTerritory)
{
${"$T.$index"}= $BrickTerritory->TerritoryID;
${"'Weightage'.$index"} = $BrickTerritory->Weightage;
}
echo $T1."-".$T2."--".$Weightage1."---".$Weightage2; exit;
}
Try changing those lines like this:
${"T$index"}= $BrickTerritory->TerritoryID;
${"Weightage$index"} = $BrickTerritory->Weightage;
In your code ${"$T.$index"} $T is searching for variable, and you should get undefined variable $T, so you have to remove $ sign, if you want to have T1, T2 variables.
After that, ${"'Weightage'.$index"}, the apostrophes between Weightage means your variable will look like 'Weightage'.1, 'Weightage'.2.. and etc.
This can be done a few different ways without variable variables AND produce a completely dynamic outcome.
Here's one: (Demo)
$array = (array)$BrickTerritorys; // cast as array
$tids = array_column($array, 'TerritoryID'); // isolate column data
$was = array_column($array, 'Weightage'); // isolate column data
$merged = array_merge($tids, $was); // add 2nd array data after 1st array data
foreach ($merged as $i => $v) {
echo str_repeat('-', $i) , $v; // increase hyphens on each iteration starting from 0
}
Output: (notice, no hardcoded echo)
HYD-2-CMD-HYD-1-CMD--40.00---60.00
I have an array in PHP that I am looping through to get content.
When echoed, the results of my array variable $myArray looks like the below
Array(
[0] => ABC
[1] => DEF
[2] => GHI
[3] => JKL
)
Array(
[0] => MNO
[1] => 123A
[2] => 123B
[3] => 123C
)
Array(
[0] => orange
[1] => yellow
[2] => green
[3] => blue
)
But when i pass this to the html data element using
data-results = "$myArray"
I get a
Notice: Array to string conversion
error.
How can this be passed as one array to the html data element?
I think , you may use the below code . It will work incase if array values having special characters .
<div data-results="<?php echo htmlspecialchars(json_encode($myArray), ENT_QUOTES, 'UTF-8'); ?>"></div>
If you want to print your array into a string equivalent, you can use:
$stringArray = print_r($array, true);
echo $stringArray;
If you wish to print it as a JSON string, you can use:
$array = array('a', 'b', 'c');
echo json_encode($array);
This has probably already been answered elsewhere, but you cannot echo an array out. You can only echo out a scalar value or an object that has a __toString() method on it.
So it's data-results="{$myArray[0][0]}" or something else in your case, since you have a multi-dimensional array. What you probably want is some sort of for loop:
foreach ($myArray as $arr) {
foreach ($arr as $value) {
echo "data-rule={$value}";
}
}
I have the following variable:
$checkbox = implode(';', $_POST['product']);
$checkbox is equal to "Product Name;Price;Unit", how can I add a break after every line?
At the moment $checkbox is equal to:
ASFP4040;18.95;1;ASFP4048;21;1;ASGS100100;25.45;1
I need it to be like:
ASFP4040;18.95;1;
ASFP4048;21;1;
ASGS100100;25.45;1;
EDIT:
I am writing this to a .TXT file, \n shows as text and doesn't actually create a new line.
As I'm not sure, how your $_POST['products'] var looks like, you might like one of these options:
If you have everything in a single array element like this
Array
(
[0] => ASFP4040
[1] => 18.95
[2] => 1
[3] => ASFP4048
[4] => 21
[5] => 1
[6] => ASGS100100
[7] => 25.45
[8] => 1
)
you could split the array into chunks and join them together
$data = implode("\n", array_map(function($chunk) {
return implode(';', $chunk);
}, array_chunk($_POST['product'], 3)));
Alternatively, if you have an array of strings like below:
Array
(
[0] => ASFP4040;18.95;1
[1] => ASFP4048;21;1
[2] => ASGS100100;25.45;1
)
a simple implode would be enough
$data = implode("\n", $_POST['product']);
Try this:
echo "'".implode("','",$checkbox)."'<br>";
You can use regular expressions to do this. Just replace my $str with your $checkbox.
$str = 'ASFP4040;18.95;1;ASFP4048;21;1;ASGS100100;25.45;1';
$str2 = preg_replace('/((?:(?:[^;]+);){3})/',"$1\n",$str);
echo $str2;
As explained in Magnus Eriksson's comment and mine, you just have to use "\n" as first parameter of your implode:
$checkbox = implode("\n", $_POST['product']);
Please notice the use of double quotes (") in order for \n to be used as a linebreak.
I have URL like this, how we recive the value
like "abc.org/result.php?rq=[1,2,3,4]&rq1=[5]" etc
Can any one help me to convert rq into array when recive the value in result.php
You can try using explode() & array_map()
$rq = $_GET['rq'];
$arr = array_map(function($v){ return trim($v, ' []');}, explode(',', $rq));
print '<pre>';
print_r($arr);
print '</pre>';
You can use json_decode to convert into array
$a = json_decode($_GET['rq']);
print_r($a);//Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
You can use get request also:
Abc.com?req[]=1&req[]=2
$_GET['req']
Return
(1,2)
I have an array in PHP and I want to remove duplicates.
I simply turned to the function array_unique() to create a new array and remove the duplicates.
Here's the code:
$unlink = array();
$unlink = array_unique($linkphoto);
foreach ($unlink as $link) {
echo $link, "<br />";
}
Still it shows duplicates! Any suggestions about what's wrong?
According to the documentation, the condition for equality is as follows:
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.
What sort of data are you using? If two items aren't string equal, then they'll both remain in the array.
We need more context in order to be able to help you, like what the contents are of $linkphoto before array_unique is applied to it. For example:
<?php
$array = Array('A','B','C','D','B');
print_r($array); // Array ( [0] => A [1] => B [2] => C [3] => D [4] => B )
$result = array_unique($array);
print_r($result); // Array ( [0] => A [1] => B [2] => C [3] => D )
?>
As #nobody_ mentioned, it will only eliminate duplicates if their string representations are the same.