trouble with array_merge, serialize and unserialize in php - 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,
)

Related

How to make array from a single quoted array

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

Getting array values sorted in new array, and then comparing with another Array

I have an array and want to get the values from it sorted and modified a bit to an other array, so I can make some comparison with yet another array
This is my array to begin with
Array (
[0] => WP_Term Object (
[term_id] => 10
...
[cat_name] => Klantenartikelen
[category_nicename] => klantenartikelen
[category_parent] => 0 )
[1] => WP_Term Object (
[term_id] => 11
...
[cat_name] => Overwin je Overgang blog
[category_nicename] => overwin-je-overgang-blog
[category_parent] => 10 )
)
I want to sort out the values of [cat_name] in to the new Array, remove one string from it ( blog) and then compare it with another Array, which looks like this
Array (
[1426787445] => Overwin je Overgang
[1426787487] => Overgangstransformatie
)
The problem with the second Array is that the key changes for every Array (membership secret code), but the values are always the same. (if it is too problematic to get the values from an Array like this, it can be hard-coded)
Then at the end I want to make a conditional logic with the comparison: if the value pairs of the two Array match, to echo a graphic element. There might be cases when one Array contains let's say 2 key/values pairs, and the other only 1, but it would need to pass true if one of the 2 is matching.
Any idea please, how this can be solved?
Given the following variables:
$data = Array (
(object) Array(
"term_id" => 10,
"cat_name" => "Klantenartikelen",
"category_nicename" => "klantenartikelen",
"category_parent" => 0
),
(object) Array(
"term_id" => 11,
"cat_name" => "Overwin je Overgang blog",
"category_nicename" => "overwin-je-overgang-blog",
"category_parent" => 10
)
);
$ref = Array (
1426787445 => "Overwin je Overgang",
1426787487 => "Overgangstransformatie"
);
You could then do this:
foreach ($data as $obj) {
// remove "blog"
$catname = str_replace(" blog", "", $obj->cat_name);
// find this name in the $ref array
$matchKey = array_search($catname, $ref);
if ($matchKey !== false) {
echo "Found '$catname' at key $matchKey", '<br>';
}
}
This produces this output:
Found 'Overwin je Overgang' at key 1426787445
At the place of the echo you could then output the image, etc...
Try this
$catname=$array_column($array, "cat_name");
$count=count($catname)
for($i=0; $i<$count; $i++){
foreach($anotherarray as $key => $value){
if($catname[$i]==$anotherarray[$key]){
echo "graphic";
}
}
}
find any error? post back

Object JSON response using PHP

I am trying to generate a JSON response using PHP that should look like this:
Records={{"country":"United States","fixed":0.20,"cellular":0.35}, {"country":"Canada","fixed":0.30,"cellular":0.45}}
But when I run the code, this is what I get:
Records={"0": {"country":"United States","fixed":0.20,"cellular":0.35}, "1":{"country":"Canada","fixed":0.30,"cellular":0.45}}
This is my PHP code:
$arr_o = array();
array_push($arr_o, array("country" => "United States", "fixed" => 0.20, "cellular" => 0.35));
array_push($arr_o, array("country" => "Canada", "fixed" => 0.30, "cellular" => 0.45));
return json_encode((object)$arr_o);
The array_push method adds the second parameter (your populated "JSON" array) to the existing empty array as an element of that array.
For example:
$a = array();
array_push($a, 1);
print_r($a)
Yields:
Array
(
[0] => 1
)
If your parameter itself is an array, then it will be appended as an element:
$b = array();
array_push($b, 1);
array_push($b, array(2, 3));
print_r($b);
Yields:
Array
(
[0] => 1
[1] => Array
(
[0] => 2
[1] => 3
)
)
If you want to append the elements of one array on to the end of an existing array, one solution is to use the array_merge method, for example:
$c = array(1);
$c = array_merge($c, array((2, 3, 4));
print_r($c);
Yields:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
See more on array_merge on the following PHP documentation: http://php.net/manual/en/function.array-merge.php
As others have already noted, the "{}" should also be converted to "[]" for the output to be valid JSON.

remove integer index an array

I am working on a website where we need to remove the index of an array where type is integer.
Have you any idea or suggestion regarding.
My array looks like this :
Array
(
[0] => first
[first] => second
[1] => second
[second] => second
[2] => third
[third] => third
[3] => forth
[forth] => v
[4] => fifth
[fifth] => fifth
)
How we can remove integer index from array.One more thing to note that we have not static array we do not know how many index is there.
Need like this :
Array
(
[first] => second
[second] => second
[third] => third
[forth] => v
[fifth] => fifth
)
Database Solution:
To get only the associative array from mysql database use: mysqli_fetch_assoc() instead of mysqli_fetch_array().
mysqli_fetch_array() fetches the entire array - integer indexes as well as column names as keys.
mysqli_fetch_assoc() only fetches the column names as keys. - thus getting rid of integer keys.
General Solution:
To do what you asked in general I would use:
foreach($array as $key => $value){
if(is_numeric($key)) unset($array[$key]);
}
You can also use is_int() if you like..
Another way to do this :-
$array1 = array("6566"=>"zd xf", "2"=>2, "c"=>3, "d"=>4, "e"=>5);
$keys=array_filter(array_keys($array1), "is_numeric");
$out =array_diff_key($array1,array_flip($keys));
print_r($out);
output :
Array
(
[c] => 3
[d] => 4
[e] => 5
)
remove the integer index value of array.
$array1=array();
$array = array(0 => first,first => second,1 => second,second => second,2 => third,third => third,3 => forth,forth => v,4 => fifth,fifth => fifth);
foreach ($array as $key=>$value){
if(gettype($key)=='integer'){
unset($key);
unset($value);
}else{
$array1[$key]=$value;
}
}
print_r($array1);
out put like this.
Array
(
[first] => second
[second] => second
[third] => third
[forth] => v
[fifth] => fifth
)

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);

Categories