I am return a serialize array from a post meta field in wordpress called groups.
here is how it looks in to post meta field.
a:2:{i:0;s:1:"1";i:1;s:1:"2";}
how can i loop trough this and run an if statement i.e.
$mydata = unserialize($meta['groups']);
print_r($mydata);
The unserialzed isnt working for me the ouput i get from the print_r is below
a:2:{i:0;s:1:"1";i:1;s:1:"2";}
which is same as above.
Any help on working with serialized and unserialzed arrays never used before.
Propably magic_quotes is active. Strip the slashes generated by it with stripslashes:
$mydata = unserialize(stripslashes($meta['groups']));
If you want to strip slashes from the whole GPC-Array use this (Credits go to this comment on PHP.net):
if (get_magic_quotes_gpc()) {
$strip_slashes_deep = function ($value) use (&$strip_slashes_deep) {
return is_array($value) ? array_map($strip_slashes_deep, $value) : stripslashes($value);
};
$_GET = array_map($strip_slashes_deep, $_GET);
$_POST = array_map($strip_slashes_deep, $_POST);
$_COOKIE = array_map($strip_slashes_deep, $_COOKIE);
}
print_r(unserialize('a:2:{i:0;s:1:"1";i:1;s:1:"2";}'));
will print
Array
(
[0] => 1
[1] => 2
)
The unserialization works just fine. How do you know if $meta['groups'] contains what you want?
Here is what I obtained using command-line PHP:
php > $x = unserialize('a:2:{i:0;s:1:"1";i:1;s:1:"2";}');
php > print_r($x);
Array
(
[0] => 1
[1] => 2
)
It seems that $meta['groups'] does not contain the serialized string.
Related
I am beginner to laravel. I am trying to access array input from my API request.
For postman, I have array as key called file_name_list and its value like ["m_profile.png","aa_image.jpg","new_pan.jpg"]. I want to access that array in my controller. That values should go into 3 seperate variables like
$profile = m_profile.png
$aadhar = aa_image.jpg
$pan = new_pan.jpg
For that I am trying to use replace and explode functions in controller.
$filenamelist1 = Str::replaceArray(array(' ','"', '[',']'),[""], $request->file_name_list);
$filename_str = explode(",",$filenamelist1);
After this I want to store values from explode array to 3 variables as mentioned above using for loop
But I am facing problems like in Str::replaceArray 2 parameter should be array and for explode 2 parameter should be string.
How should I use replace and explode to get required result? please guide. Thanks in advance.
You can use list method like below:
list( $profile , $adhar, $pan) = $request->file_name_list;
Check the Docs
If Your array size fixed then you assign that by using list
list( $profile,$adhar,$pan) = $request->file_name_list;
<?php
$value = '["m_profile.png","aa_image.jpg","new_pan.jpg"]';
$value = str_replace("[","",$value); // clean [
$value = str_replace("]","",$value); // clean ]
$arrayValues = explode('","',$value); // explode with ","
print_r($arrayValues);
output
Array (
[0] => "m_profile.png
[1] => aa_image.jpg
[2] => new_pan.jpg"
)
Replace " when you access the values
I would like to search value of order using array_search function i have tried following ways but it does not work.
printed array display output
PostDaataArray
(
[order_id] => 5464
)
$currentKey=array_search($orderId,$postedData);
also tried $currentKey=array_search($orderId,array_column($postedData, 'order_id'));
But when i tried to search array using array_search function it does not work also not showing error as well.
If previously data in JSON format then decode it:
$postedData = json_decode($postedData,true);
You can use in_array():
if(in_array($orderId,array_column($postedData, 'order_id'))) //check value is in array
{
$key = array_search($orderId,array_column($postedData, 'order_id')); //return index or key of array
}
else
{
//order id not in array
}
try this:
$PostDaataArray=array("order_id"=>"5464");
foreach($PostDaataArray as $key=>$order_id){
if($order_id=="5464"){
// match found.
}
}
How would I setup an associative array to reference specific values at different sections of a page. My function:
<?php
function park_data($park_page_id) {
$data = array();
if($park_page_id){
$data = mysql_fetch_assoc(mysql_query("SELECT * FROM `park_profile` WHERE `park_id` = $park_page_id"));
return $data;
}
}
?>
My print_r:
<?php
print_r (park_data(1));
?>
Produces the following associative array:
Array ( [park_id] => 1 [park_name] => Kenai Fjords [park_address] => 1212 4th Avenue [park_city] => Seward [park_state] => Alaska [park_zip] => 99664)
How would I print just the [park_name] value from this array?
From the docs:
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
// on PHP 5.4
print_r(park_data(1)['park_name']);
// earlier versions
$tmp = park_data(1);
print_r($tmp['park_name']);
$park=park_data(1);
echo $park['park_name'];
To output custom formatted text in general, and in this case to output only a single array's key value, use echo, because print_r() called on an array displays the whole array's structure and content, and that's not what you want:
<?php
// code
$park_data=park_data(1);
echo $park_data["park_name"];
// code
?>
I have an array what I encode as json and I save it to database. The array looks like
$myarray = array(
'test'=>array('key1'=>'1',
'key2'=>'2',
'key3'=>'3'),
'test2' =>array('key4'=>'1',
'key5'=>''
)
);
json_encode($myarray);
the saved json in my database looks like
{
"test": {"key1":"1",
"key2":"2",
"key3":"3"
},
"test2": {"key4":"1",
"key5":""
}
}
MYSQL save
$sql = "UPDATE my_table SET params= '".json_encode($param )."' WHERE id ='".$key."'";
Than when I retrieve the json string from database and trying to rebuild the array with json_decode($json, true); outputs null
You could serialize the data rather than storing it as json.
$sql = "UPDATE table SET field='".serialize($myarray)."' WHERE ...";
Then when you want to recreate the array, just pull it out of the table and unserialize() it. It's not human readable in the database; however this technique is fast and works well for storing arrays in the db. If the data is needed by your js scripts then json_encode() it after you unserialize() it.
Have you tryed to use addslashes() and stripslashes() php functions ?
Try:
To update your table:
$sql = "UPDATE my_table SET params='".addslashes(json_encode($myarray))."' WHERE id ='".$key."';";
to read from table:
$sql = "SELECT params FROM my_table WHERE id='".$key."';";
...code to read row...
$myparams = stripslashes($row['params']);
also you can try the a custom function for a multidimensional array from php manual called stripslashes_deep() see http://www.php.net/manual/en/function.stripslashes.php (EXAMPLE #2)
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
print_r($array);
// Output
Array
(
[0] => f'oo
[1] => b'ar
[2] => Array
(
[0] => fo'o
[1] => b'ar
)
)
foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];
echo "$_GET[$field]";
echo "<br>";
}
print_r($datarray);
This is the output I am getting. I see the data is there in datarray but when
I echo $_GET[$field]
I only get "Array"
But print_r($datarray) prints all the data. Any idea how I pull those values?
OUTPUT
Array (
[0] => Array (
[0] => Grade1
[1] => ln
[2] => North America
[3] => yuiyyu
[4] => iuy
[5] => uiyui
[6] => yui
[7] => uiy
[8] => 0:0:5
)
)
EDIT: When I completed your test, here was the final URL:
http://hofstrateach.org/Roberto/process.php?keys=Grade1&keys=Nathan&keys=North%20America&keys=5&keys=3&keys=no&keys=foo&keys=blat&keys=0%3A0%3A24
This is probably a malformed URL. When you pass duplicate keys in a query, PHP makes them an array. The above URL should probably be something like:
http://hofstrateach.org/Roberto/process.php?grade=Grade1&schoolname=Nathan®ion=North%20America&answer[]=5&answer[]=3&answer[]=no&answer[]=foo&answer[]=blat&time=0%3A0%3A24
This will create individual entries for most of the fields, and make $_GET['answer'] be an array of the answers provided by the user.
Bottom line: fix your Flash file.
Use var_export($_GET) to more easily see what kind of array you are getting.
From the output of your script I can see that you have multiple nested arrays. It seems to be something like:
$_GET = array( array( array("Grade1", "ln", "North America", "yuiyyu", "iuy", "uiyui", "yui","uiy","0:0:5")))
so to get those variables out you need something like:
echo $_GET[0][0][0]; // => "Grade1"
calling echo on an array will always output "Array".
print_r (from the PHP manual) prints human-readable information about a variable.
Use <pre> tags before print_r, then you will have a tree printed (or just look at the source. From this point you will have a clear understanding of how your array is and will be able to pull the value you want.
I suggest further reading on $_GET variable and arrays, for a better understanding of its values
Try this:
foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];
echo $_GET[$field]; // you don't really need quotes
echo "With quotes: {$_GET[$field]}"; // but if you want to use them
echo $field; // this is really the same thing as echo $_GET[$field], so
if($label == $_GET[$field]) {
echo "Should always be true<br>";
}
echo "<br>";
}
print_r($datarray);
It's printing just "Array" because when you say
echo "$_GET[$field]";
PHP can't know that you mean $_GET element $field, it sees it as you wanting to print variable $_GET. So, it tries to print it, and of course it's an Array, so that's what you get. Generally, when you want to echo an array element, you'd do it like this:
echo "The foo element of get is: {$_GET['foo']}";
The curly brackets tell PHP that the whole thing is a variable that needs to be interpreted; otherwise it will assume the variable name is $_GET by itself.
In your case though you don't need that, what you need is:
foreach ($_GET as $field => $label)
{
$datarray[] = $label;
}
and if you want to print it, just do
echo $label; // or $_GET[$field], but that's kind of pointless.
The problem was not with your flash file, change it back to how it was; you know it was correct because your $dataarray variable contained all the data. Why do you want to extract data from $_GET into another array anyway?
Perhaps the GET variables are arrays themselves? i.e. http://site.com?var[]=1&var[]=2
It looks like your GET argument is itself an array. It would be helpful to have the input as well as the output.