How to make array from a single quoted array - php

I have no idea How to convert a single quote array into array;
FOR Example:-
I have
$Array = '["ID" => 9, "Value" => [40,15,20,25,30]]';
print_r($Array);
Then it is showing like string not an array
["ID" => 9, "Value" => [40,15,20,25,30]]
so how to convert this into array
like the result will show like this
Array
(
[ID] => 9
[Value] => Array
(
[0] => 40
[1] => 15
[2] => 20
[3] => 25
[4] => 30
)
)
May be you have why i am putting array in single quote but this is not i am putting.
I Getting an array from DB after group_concat in mysql
This is the array
Array
(
[0] => Array
(
[GPN] => A
[PKGID] => PKG01
[Output] => ["ID" => 9, "Value" => [40,15,20,25,30]]
)
)
Here the Output is element coming like it's a string

You can do this but it might be dangerous:
$Array = '["ID" => 9, "Value" => [40,15,20,25,30]]';
eval('$Array = '.$Array.';'); // Could be dangerous
echo '<pre>';
print_r($Array);
echo '</pre>';
In my example above, $Array is assumed to be data coming from your database such as [Output] => ["ID" => 9, "Value" => [40,15,20,25,30]]. Since it is coming from the database then that means the possibility exists for the DB data to be malicious and eval() will gladly run anything you give it.

You can use eval to parse the string as php code like this:
$s = '["ID" => 9, "Value" => [40,15,20,25,30]]';
eval('$a = ' . $s . ';');
print_r($a);
This will work only with php 5.4 and up
CAUTION
If this string contains data from user then it is not safe to use eval.
Alternative solution
If you are the one who populate the database records, i suggests to serialize Output values as json, using json_encode, before insert to database.
Then you can use json_decode to access data as array.

<?php
$str = '["ID" => 9, "Value" => [40,15,20,25,30]]';
$array = eval('return ' . $str . ';');
var_export($array);
Output:
array (
'ID' => 9,
'Value' =>
array (
0 => 40,
1 => 15,
2 => 20,
3 => 25,
4 => 30,
),
)

So, your question is basically how to convert string representation of php array to php array. I don't know any tools for this, however you can use eval function.
$arr = [];
eval('$arr=' . $Array . ';');
// $arr contains php array
However this is not recommendable, because you can execute arbitrary code which undermines security of your application. Before using it you should make sure that $Array does not contain any malicious code and all strings are escaped.
If you run your application as a root user then it is even more dangerous. For example:
$Array = 'true?print_r($_SERVER['REQUEST_TIME']):0'
The above code will print all the server data of your application.

I think this solution.
$array = [
"ID" => 9,
"Value" => [40,15,20,25,30],
];
print_r($array);
Output :
/* Array ( [ID] => 9 [Value] => Array ( [0] => 40 [1] => 15 [2] => 20
[3]=> 25 [4] => 30 ) ) */
for other array :
$array =[
"0" => [
"GPN" => A,
"PKGID" => PKG01,
"Output" =>
[
"ID" => 9,
"Value" => [40,15,20,25,30]
]
]
];
print_r($array);
And output :
/*Array ( [0] => Array ( [GPN] => A [PKGID] => PKG01 [Output] => Array ( [ID] => 9 [Value] => Array ( [0] => 40 [1] => 15 [2] => 20 [3] => 25 [4] => 30 ) ) ) ) */
advise : the name "PKG01".
psr-1 : constants MUST be declared in all upper case
source : psr-1

Related

PHP search JSON without looping

I have a large JSON array which is the result of querying the API of an Icinga2 monitoring system.
I have used json_decode like this in my code to decode it:
$response = json_decode($array, true);
and I can see the output looks like this:
Array
(
[results] => Array
(
[0] => Array
(
[attrs] => Array
(
[__name] => HOSTNAME0
[acknowledgement] => 0
[acknowledgement_expiry] => 0
...
...
[state] => 0
[state_type] => 1
[meta] => Array
(
)
[name] => HOSTNAME0
[type] => Host
)
[1] => Array
(
[attrs] => Array
(
[__name] => HOSTNAME1
[acknowledgement] => 0
[acknowledgement_expiry] => 0
...
...
[state] => 0
[state_type] => 1
[meta] => Array
(
)
[name] => HOSTNAME1
[type] => Host
)
There are 400 Records in total and it's quite a complex structure but the only bits I am really interested in are the name and state fields.
Basically my script has a list of 150 hostnames from another source and what I want to do is for each hostname, search for it in the array and return the value of the state field for that host.
So far I've been struggling to do this without looping through the entire array for each of the 150 hostnames. There must be a more efficient way to do a lookup in the array based on a hostname and return a single value but I can't figure it out.
Given, the name field has no logical sorting inside the json result, there is no way to look at least once at each element. If they are sorted alphabetical, you could use a simple binary search, which would give you the result in O(log(n)).
The other thing is, if you have to search for multiple names, you could put them inside an name assiciated array. This way, you only have an initial overhead of O(n) building the list and each following search would return you the state on O(1).
// building the array
$states = [];
foreach ($items as $item) {
$states[$item['name']] = $item['state'];
}
looking for HOSTNAME1
$state = $states['HOSTNAME1'];
I'm hoping that I've got the source data array in the correct layout as the format was a bit confusing from the original question. But the main idea is to use array_column to extract the "attrs" and key the result by the "name" element of this array.
$response = Array(
"results" => Array(
0 => Array(
"attrs" => Array(
"__name" => "HOSTNAME0",
"acknowledgement" => 0,
"acknowledgement_expiry" => 0,
"state" => 0,
"state_type" => 1
),
"name" => "HOSTNAME0",
"type" => "Host"
),
1 => Array(
"attrs" => Array(
"__name" => "HOSTNAME1",
"acknowledgement" => 0,
"acknowledgement_expiry" => 0,
"state" => 2,
"state_type" => 1
),
"name" => "HOSTNAME1",
"type" => "Host1"
)
)
);
$extract = array_column($response["results"], "attrs", "name");
print_r($extract);
With the sample data, this gives...
Array
(
[HOSTNAME0] => Array
(
[__name] => HOSTNAME0
[acknowledgement] => 0
[acknowledgement_expiry] => 0
[state] => 0
[state_type] => 1
)
[HOSTNAME1] => Array
(
[__name] => HOSTNAME1
[acknowledgement] => 0
[acknowledgement_expiry] => 0
[state] => 2
[state_type] => 1
)
)
So to find any server by name, you'd use
echo "HOSTNAME1=".$extract["HOSTNAME1"]["state"].PHP_EOL;
If you only wanted the state field (as you asked for) and wanted to simplify the array, you can then use...
array_walk($extract, function(&$data) {$data=$data["state"];});
print_r($extract);
The array_walk() goes through the array and just copies the state field to be the entry, so the result of this is...
Array
(
[HOSTNAME0] => 0
[HOSTNAME1] => 2
)
So now you just do...
echo "HOSTNAME1=".$extract["HOSTNAME1"].PHP_EOL;

Get array value by dynamic key in php

maybe I am totally blind but i have an array:
Array ( [p541] => 1 [p747] => 1 [p792] => 1 [p968] => 1 [p2157] => 1 [clickeditem] => 0WCr9ParDzLD9wpctknt0XErhOZcX33wXfgGDNpSoIo= [actualtime] => 11832 [timekey] => 1406227645 [actualuser_id] => V58yD4MQ2ZwTumjivhhQL/BSFXsu0Dvoj0bxp7Tu8PM= [timeout] => 0 [report_misuse] => 0 [A1] => 5RC52CZHPV8f0Zw+FYGZel5Ay2YcLVjrY8MBplz1zJA= [B1] => 0WCr9ParDzLD9wpctknt0XErhOZcX33wXfgGDNpSoIo= [B2] => KnCK/vIcQ5PAwJxjUMh0w+NTM+TqdVG9+Tiyi0U9QWM= [B3] => DhT8qBQFQC+dE/Rku7wdMJ4bw6dtFp8hzfmxPMCrItQ= [B4] => ZE30ASB6IUQglpXNiOUxdmiYpJnEbuKKXIaUZO9w4mU= [B5] => IXyGTO6V/8uZOK5y81DnI58xumZ0CIkFsTQwUWJ2CyE= [pageloadtime] => 0.179646 [option] => com_findme [view] => pair )
but I want to get the value for "p541"
$name= "p541";
$value = $array [$name];
does not work ???
If your array variable is named $array, try this:
$value = $array['p541'];
What you're doing is creating a new array named $value containing the variable $name, which is not what we want.
Your array items need to be comma separated and not within [ ] if you're declaring associative arrays like that. You also need to save your array to a variable so you can access it.
$value = array('p541' => 1, 'p747' => 2, 'p792' => 3);
then this...
$value['p541']
will equal 1

trouble with array_merge, serialize and unserialize in php

I have to do this:
take an associative array and insert it into a field in my database so I can re-use it as associative array. [DONE with serialize($associativeArray)]
take the associative array from the database and view as array. [DONE with unserialize($arraySerializedBefore)]
Merge an array already in the database (serialized) with an array just created.
For example:
Array
(
[1] => 'nanananana,lol,',
[2] => 'laaaaalalalala,asd,',
[3] => 'r0tfl,lmfao,ahah,'
)
Second array to merge with the first:
Array
(
[1] => 'dunnoWhat,write,',
[3] => 'hello,wooorld,'
)
So I need a final array like this:
Array
(
[1] => 'nanananana,lol,\N,dunnoWhat,write,',
[2] => 'laaaaalalalala,asd,',
[3] => 'r0tfl,lmfao,ahah,\N,hello,wooorld,'
)
If you see it merge it using the key, if they have the same key, it adds a "\n" to go in a new line (the same of BR tag...it's only an example) and after it add the string of the second array correspondent to the key. However if you don't understand watch the example and you will.
Thanks
I just was wondering if it's possible to resolve with one functional block (like functional programming). It is:
$foo = [
0 => "test zero",
1 => "test one",
2 => "test two",
3 => "test three"
];
$bar = [
1 => "test four",
5 => "test five",
3 => "test six",
4 => "test seven"
];
$result =
array_diff_key($foo, $bar)
+
array_combine(
$y = array_keys(array_intersect_key($foo, $bar)),
array_map(function($x) use ($foo, $bar)
{
return $foo[$x]."\n".$bar[$x];
}, $y)
)
+
array_diff_key($bar, $foo);
Traverse the second array using a foreach and match its keys with the one with the first array and if match found, Update the first array by concatenation.
<?php
$arr1=Array(1 => 'nanananana,lol,',2 => 'laaaaalalalala,asd,',3 => 'r0tfl,lmfao,ahah,');
$arr2=Array(1 => 'dunnoWhat,write,',3 => 'hello,wooorld,');
$i=min(array_keys($arr1));
foreach($arr2 as $k=>$val)
{
if(array_key_exists($k,$arr1))
{
$arr1[$k].='\N, '.$val;
}
}
print_r($arr1);
OUTPUT :
Array
(
[1] => nanananana,lol,\N, dunnoWhat,write,
[2] => laaaaalalalala,asd,
[3] => r0tfl,lmfao,ahah,\N, hello,wooorld,
)

Reducing multidimensional array

I have the following multidimensional array:
Array
(
[0] => Array
(
[area] => 5
[estante] => 5
[anaquel] => 5
[no_caja] => 5
[id_tipo] => 3
[nombre_tipo] => Administrativo
)
[1] => Array
(
[area] => 5
[estante] => 5
[anaquel] => 5
[no_caja] => 5
[id_tipo] => 1
[nombre_tipo] => Copiador
)
[2] => Array
(
[area] => 5
[estante] => 5
[anaquel] => 5
[no_caja] => 5
[id_tipo] => 2
[nombre_tipo] => Judicial
)
)
and I want to reduce it by having all the different values (intersection) between them. The dimension of the array may change (I'm retrieving the info from a database). I have thought in using functions like array_reduce and array_intersect, but I have the problem that they work only with one-dimension arrays and I can't find the way to pass an indefinite (not previous known) number of parameters to these function. I'd like to have an output like this:
Array([0]=>Copiador, [1]=>Administrativo, [2]=>Judicial).
How can I do this?
Thanks in advance.
$arr=array(
array (
'area' => 5 ,
'estante' => 5 ,
'anaquel' => 5,
'no_caja' => 5,
'id_tipo' => 3,
'nombre_tipo' => 'Administrativo'),
array (//etc.
)
);
$fn=function(array $a, $k){
if(array_key_exists($k,$a)) return $a[$k];
};
$b=array_map($fn,$arr,array_fill(0,count($arr),'nombre_tipo'));
print_r($b);
/*
Array
(
[0] => Administrativo
[1] => Copiador
[2] => Judicial
)
*/
$reduced = array();
foreach ($oldarray as $value) {
$reduced[] = $value['nombre_tipo'];
}
Although, a better solution may be to just modify your SQL query so you get the correct data to begin with.
Note: you can also do it with array_reduce, but I personally prefer the method above.
$reduced = array_reduce($oldarray,
function($a, $b) { $a[] = $b['nombre_tipo']; return $a; },
array()
);
This task is exactly what array_column() is for -- extracting columnar data.
Call this:
var_export(array_column($your_array, 'nombre_tipo'));
This will output your desired three-element array. ...I don't understand the sorting in your desired output.
Seems like you want array_map
$newArr = array_map(function($a) {
return $a['nombre_tipo'];
}, $oldArr);
var_dump($newArr);

Creating arrays dynamically using PHP

Hey folks, please lend a hand to a PHP beginner. I'm trying to put a load of dynamically created variabled into an array to re-read later, reason is a SOAP message sent is a mess and im trying to create a less complicated array:
$placea = "place a";
$placeb = "place b";
$myarray = array();
echo "<pre>";
print_r($myarray);
echo "</pre>";
what i want to be able to do:
Array
(
[0] => [Place A] => Array
(
[0] => [Accommodation] => Array
(
[RoomId] => 001
[RoomAvail] => true
[Date] => 12.04.2011
)
[1] => [Accommodation] => Array
(
[RoomId] => 002
[RoomAvail] => true
[Date] => 12.04.2011
)
) Array
(
[1] => [Place B] => Array
(
[0] => [Accommodation] => Array
(
[RoomId] => 101
[RoomAvail] => true
[Date] => 12.04.2011
)
[1] => [Accommodation] => Array
(
[RoomId] => 102
[RoomAvail] => true
[Date] => 12.04.2011
)
)
)
how would i write that out in php? sorry if its bleek and/or the array structure is incorrect
So you just need to use the array initializer repetitively.
If you want to initialize an array in PHP with some values, say 1 through 4, you make a call like:
$foo = array(1, 2, 3, 4);
And if you want to make an associative array, where you store some key/value pairs, you make a call like:
$foo = array('key' => 'value', 'other key' => 'other value');
But you can of course nest calls, and mix and match layers of associative and non associative arrays to achieve something like your example, e.g.:
$foo = array(
'Place A' => array(
// note use of first array on the next line is
// to generate structure like [0] => 'Accomodation' => ...
array('Accomodation' => array(
'RoomId' => '001',
'RoomAvail' => true,
'Date' => '12.04.2011')
)),
array('Accomodation' => array(
'RoomId' => '002',
'RoomAvail' => true,
'Date' => '12.04.2011')
))
),
'Place B' => array(
array('Accomodation' => array(
'RoomId' => '101',
'RoomAvail' => true,
'Date' => '12.04.2011')
)),
array('Accomodation' => array(
'RoomId' => '102',
'RoomAvail' => true,
'Date' => '12.04.2011')
))
)
);
This will very nearly produce what you're looking for, to make it replicate exactly what you have you would wrap each 'Place A' with an array and each "place" would get its own assignment to some variable $foo (I assumed this wasn't actually what you wanted and wrote something maybe slightly more intuitive).
If you want to have a 'less complicated' array, you have a two arrays, one fore place a and one for place b and then merge them using array_merger() http://www.php.net/manual/en/function.array-merge.php.
Study up on the array functions control structures in the manual. Many different ways of achieving bloated arrays uglying up your code.
This would dynamically create an array.
foreach($soapResponse as $key1 => $value1){
foreach($value as $key2 => $value2){
// $key1 = Place A or B
// value1 = array of values
$arrayResponse[$key1][$key2] = $value2;
}
}

Categories