Is there any way besides for explode to convert a php string that looks like: "[2,0,[]]" into an array?
My array output should be like:
array(2,0,array())
And "[2,0,[1,2,3,4]]" this sting should be:
array(2,0,array(1,2,3,4))
I do not want to use explode because it just seems like to much code for a very simple task. in javascript it is a one liner:
JSON.parse('[2,0,[1,2,3,4]]');
Your input looks like a JSON string, which can be converted with json_decode() function :
json_decode("[2,0,[]]", true);
/*
Array (
0 => 2,
1 => 0,
2 =>
Array (
),
)
*/
As specified by Tareq Mahmood json_decode would work but in case you want to do it from scratch:
<?php
$string = "[2,0,[1,2,3,4,]]";
$i = 0;
$array = array();
$handlerCount = 0;
$arrayTmp = array();
$countArr2=0;
while(isset($string[$i])){
switch($string[$i]){
case ",":
break;
case "[":
$handlerCount++;
break;
case "]":
$handlerCount--;
break;
default:
if($handlerCount == 1){
$array[$i] = (int)$string[$i];
}else{
$arrayTmp[$countArr2] = (int)$string[$i];
$countArr2++;
}
}
$i++;
}
array_push($array,$arrayTmp);
var_dump($array);
?>
[Proof of concept]
array(3) {
[1]=>
int(2)
[3]=>
int(0)
[4]=>
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
}
}
Related
I have explode here is the result of var_dump:
and I want get the result from explode:
7 [remove other string]
0 [if contain "-"]
0 [if contain "-"]
0 [if contain "-"]
Here, I just used comma as delimiter:
var_dump (explode(",", $rowData[0][13]));
die();
Does anyone have the solution to solved this?
Thank You.
Use array_map() function and in it use filter_var() to sanitize number value.
Try
$rowData = ['JJ7', 'B-', 'S-', 'M-'];
$result = array_map(function($v) {
return abs((int) filter_var($v, FILTER_SANITIZE_NUMBER_INT));
}, $rowData );
var_dump( $result );
//output
// array(4) { [0]=> int(7) [1]=> int(0) [2]=> int(0) [3]=> int(0) }
<?php
$data_result = explode(",", $rowData[0][13])
for($data_count=0;$data_count<count($data_result);$data_count++)
{
if(substr($data_result[$data_count], -1) == '-')
{
echo $data_result[$data_count]
}
}
?>
Hello I've multidimensional array that looks like that:
array(13890) {
[0]=>
array(2) {
["Icd"]=>
array(2) {
["id"]=>
int(111)
["nazwa"]=>
string(6) "DŻUMA"
}
["ProjectIcd"]=>
array(0) {
}
}
[1]=>
array(2) {
["Icd"]=>
array(2) {
["id"]=>
int(566)
["nazwa"]=>
string(7) "ŚWINKA"
}
["ProjectIcd"]=>
array(0) {
}
}
An so on.
I want to change it so it looks something like that:
array(13890) {
[0]=> array(2) {
["id"]=>
int(111)
["text"]=>
string(6) "DŻUMA"
}
How is this possible to do?
I want to add, I want to convert the array to json and feed it to select2 js in ajax.
Will that be a problem or not?
Short solution using array_map function:
// $arr is your initial array
$new_arr = array_map(function($a){
return ['id' => $a['Icd']['id'], 'text' => $a['Icd']['nazwa']];
}, $arr);
So you can simple create a new array and add there the values, which you want based on the old array. Then you convert the array to a json string with the php function json_encode():
$array = array("text"=>$old_array[0]["Icd"]["nazwa"]);
echo json_encode($array);
I hope this is something that you want.
$res = [];
$i = 0;
foreach($array as $arr) {
//get keys
if (count($arr) > 0) {
$keys = array_keys($arr);
// loop through the keys and fetch data of those keys
// put in array
foreach($keys as $key) {
if ($arr[$key]) {
$res[$i]['id'] = $arr[$key]['id'];
$res[$i]['text'] = $arr[$key]['nazwa'];
}
$i++;
}
}
}
print_r($res);
// To change array to json
echo json_encode($res);
I have a array and I need unique contents. How can I get rid of duplicates in this $tmparray:
array(176) {
[0]=>
array(2) {
[0]=>
string(22) "/ads/67006/didi"
[1]=>
string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"
}
[1]=>
array(2) {
[0]=>
string(22) "/ads/67006/didi"
[1]=>
string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"
}
[2]=>
array(2) {
[0]=>
string(22) "/ads/67006/didi"
[1]=>
string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"
}
[3]=>
array(2) {
[0]=>
string(19) "/ads/67010/sylvesta"
[1]=>
string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"
}
[4]=>
array(2) {
[0]=>
string(19) "/ads/67010/sylvesta"
[1]=>
string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"
}
[5]=>
array(2) {
[0]=>
string(19) "/ads/67010/sylvesta"
[1]=>
string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"
}
But I want it to look like: (Only unique contents.)
array(176) {
[0]=>
array(2) {
[0]=>
string(22) "/ads/67006/didi"
[1]=>
string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"
}
[1]=>
array(2) {
[0]=>
string(19) "/ads/67010/sylvesta"
[1]=>
string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"
}
}
I have tried with:
array_unique($tmparray);
array_unique can't do what I want. Anyone have a idea how to solve this?
your question seems duplicate of this
How to remove duplicate values from a multi-dimensional array in PHP
i guess array_map will solve your problem
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
You can use this code:
$newarray= array();
foreach ($tmparray as $value) {
if (!in_array($value,$newarray)) {
$newarray[ ] = $value;
}
}
var_dump($newarray);
I assume that by duplicate you mean two items where either elements are matching, since you are mapping ads to their pictures, therefore:
$target = array();
$elementCount = count($tmparray);
$newElementCount = 0;
for ($i = 0; $i < $elementCount; $i++) {
$found = false;
for ($j = 0; (!$found) && (j < $newElementCount); j++) {
$found = $target[$j][0] === $tmparray[$i][0] || $target[$j][1] === $tmparray[$i][1];
}
if (!$found) {
$target[$newElementCount++]=$tmparray[$i];
}
}
PHP array_unique is used only for single dimensional arrays, for multidimensional you can do this by serializing multidimensional array, like below
<?php
$dataArray = [
0=>["/ads/67006/didi","/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"],
1=>["/ads/67010/sylvesta","/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"],
2=>["/ads/67006/didi","/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"],
3=>["/ads/67010/sylvesta","/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"],
];
$serilaized = [];
$newArr = [];
### serilaize each node of multi array and create a new single dimention array..
foreach($dataArray as $val){
$serilaized[] = serialize($val);
}
### now perform array unique..
$serilaized_unique = array_unique($serilaized);
## unserialize each node of uniqur array..
foreach($serilaized_unique as $val){
$newArr[] = unserialize($val);
}
echo "<pre>";print_r($newArr);
?>
This will give you:
Array
(
[0] => Array
(
[0] => /ads/67006/didi
[1] => /Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg
)
[1] => Array
(
[0] => /ads/67010/sylvesta
[1] => /Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg
)
)
In short you can perform this in single line code with array_map
$dataArray = array_map('unserialize', array_unique(array_map('serialize', $dataArray)));
I got it working with this line:
$tmparray = array_unique($tmparray, SORT_REGULAR);
int twodim[5][8];
int threedim[3][5][8];
How to create fixed length multi dimensional array in php as we create in c++ ?
To create fixed array you should use SplFixedArray from Standard PHP Library extension:
The SplFixedArray class provides the main functionalities of array. The main differences between a SplFixedArray and a normal PHP array is that the SplFixedArray is of fixed length and allows only integers within the range as indexes. The advantage is that it allows a faster array implementation.
It's not very PHP-like, but you can use this function (based on Grzegorz' SplFixedArray hint) to generate fixed sized arrays of any dimension.
function createFixedArray() {
$args = func_get_arg(0);
$array = new SplFixedArray($args[0]);
if (isset($args[1])) {
$newArgs = array_splice($args, 1);
for ($i=0; $i<$args[0]; $i++) {
$array[$i] = createFixedArray($newArgs);
}
}
return $array;
}
Example use:
$fixedArray = createFixedArray(array(2, 2, 2));
$fixedArray[0][0][0] = 0;
$fixedArray[0][0][1] = 1;
$fixedArray[0][1][0] = 1;
$fixedArray[0][1][1] = 0;
$fixedArray[1][0][0] = 1;
$fixedArray[1][0][1] = 0;
$fixedArray[1][1][0] = 0;
$fixedArray[1][1][1] = 1;
var_dump($fixedArray);
Generates
object(SplFixedArray)#1 (2) {
[0]=>
object(SplFixedArray)#2 (2) {
[0]=>
object(SplFixedArray)#3 (2) {
[0]=>
int(0)
[1]=>
int(1)
}
[1]=>
object(SplFixedArray)#4 (2) {
[0]=>
int(1)
[1]=>
int(0)
}
}
[1]=>
object(SplFixedArray)#5 (2) {
[0]=>
object(SplFixedArray)#6 (2) {
[0]=>
int(1)
[1]=>
int(0)
}
[1]=>
object(SplFixedArray)#7 (2) {
[0]=>
int(0)
[1]=>
int(1)
}
}
}
I have a multi-dimensional array which I need to pass to Google Charts. The script is called via Ajax, runs three times and then passes back the array encoded with json_encode. I then needed to add headers to the array so I used array_unshift().
Here is the script
$dataArray = array();
$i = 0;
foreach ($arrSiteValue as $key => $value) {
if($i == 3){
break;
}
$dataArray[$key] = $value;
$i ++;
}
array_unshift($dataArray, array("Terms","Visits"));
echo json_encode($php_array);
Here is what is returned:
Note: Where it says (not set) and (not provided), They are correct values for the string and need to be that.
The value of the key should be an integer however it is getting passed back as a string
How can I get it so that the value is added as an integer?
Here is a dummy array (that works) to show what format the array should be outputted like:
$php_array = array(
array('Terms', 'Visits'),
array('test', 90),
array('joke', 90),
array('funny', 11)
);
And this is what this dummy array ouputs (which is how I need it):
*When I change the line to include (int) as recommenced by some of the users here I get this result:
Edit
These are the lines that get the data from the Google Analytics Library:
if (!$_GET["rangeStartDate"]) {
$startDate = date("Y-m-d", mktime(0, 0, 0, date("m")-1, date("d")-1, date("Y")));
$endDate = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d")-1, date("Y")));
} else {
$startDate = $_GET["rangeStartDate"];
$endDate = $_GET["rangeEndDate"];
}
$metrics = "ga:visits";
$dimensions = "ga:keyword";
$filters = "ga:keyword==(not set)";
$optParams = array('dimensions' => $dimensions, 'filters' => $filters);
$arrSiteResults = $service->data_ga->get($ids,$startDate,$endDate,$metrics,$optParams);
$notSetVisits = $arrSiteResults['rows'][0][1];
// Visits and Page Views
$metrics = "ga:visits";
$dimensions = "ga:keyword";
$optParams = array('dimensions' => $dimensions, 'sort' => '-ga:visits', 'max-results' => '12');
$arrSiteResults = $service->data_ga->get($ids,$startDate,$endDate,$metrics,$optParams);
$arrSiteValue = $arrSiteResults['rows'];
Here is var_dump of: $arrSiteValue:
array(12) { [0]=> array(2) { [0]=> string(9) "(not set)" [1]=> string(4) "2582" } [1]=> array(2) { [0]=> string(14) "(not provided)" [1]=> string(4) "1504" } [2]=> array(2) { [0]=> string(10) "compass fm" [1]=> string(3) "149" } [3]=> array(2) { [0]=> string(18) "compass fm grimsby" [1]=> string(2) "25" } [4]=> array(2) { [0]=> string(9) "compassfm" [1]=> string(2) "10" } [5]=> array(2) { [0]=> string(15) "compassfm.co.uk" [1]=> string(1) "9" } [6]=> array(2) { [0]=> string(16) "compass fm radio" [1]=> string(1) "8" } [7]=> array(2) { [0]=> string(18) "grimsby rugby club" [1]=> string(1) "8" } [8]=> array(2) { [0]=> string(13) "compass radio" [1]=> string(1) "7" } [9]=> array(2) { [0]=> string(21) "compass radio grimsby" [1]=> string(1) "5" } [10]=> array(2) { [0]=> string(19) "www.compassfm.co.uk" [1]=> string(1) "5" } [11]=> array(2) { [0]=> string(15) "compass fm news" [1]=> string(1) "4" }}
PHP's json_encode function will always encode PHP strings as JSON strings. If the data goes into JSON as a string, it was a string in PHP as well.
Why it is a string in PHP is an interesting question. Perhaps the data comes from a database?
In any case, the solution is to convert the string into an integer (with (int)) when you pass it to json_encode:
$dataArray[$key] = (int) $value;
NB that I wouldn't check with is_numeric. The API is clearly expecting the value to be an integer, so I'd suggest you provide one. If the value can't be converted, it will be 0, which is probably a sensible default in your case.
OK, the above code is wrong, because it attempts to convert the array into an integer. The problem, then, is how that array is constructed. It's very hard to help you fix this if you can't show the line of code that creates the value that isn't working.
But I'll bet £5 that the solution is (int).
Per the latest update. I hadn't realised the data was coming from Google Analytics. You get the data and it looks like this: [1]=> string(4) "2582". That is obviously a string that contains number characters. You need to convert this to a number using (int). You should do this in your loop:
if($i == 3){
break;
}
$value[1] = (int) $value[1]; // cast the number to an int
$dataArray[$key] = $value;
Try changing assignment line to this:
$dataArray[$key] = is_numeric($value) ? (int)$value : $value;
Note: it's not a generic solution, but will work in this particular case.
Use intval() (assuming they're all integers, otherwise use floatval()).
$dataArray = array();
$i = 0;
foreach ($arrSiteValue as $key => $value) {
if($i == 3){
break;
}
$dataArray[$key] = intval($value);
$i ++;
}
array_unshift($dataArray, array("Terms","Visits"));
echo json_encode($php_array);
Assuming you can't change the data at its source (you say it is coming from an external API), you may have to explicitly convert the string to an integer yourself:
$dataArray[$key] = intval($value, 10);
or
$dataArray[$key] = (int)$value;
You may want to check that $value is actually a valid number before converting it - use is_numeric for that