merging json array only with same keys - php

I have two Json arrays like below:
$a='[{"type":"text","req":0,"name":"user"},{"type":"text","req":0,"name":"org"},'
. '{"type":"textarea","label":"Notes","req":0},'
. '{"type":"text","label":"text1","req":0},'
. '{"type":"textarea","label":"Notes","req":0},'
. '{"type":"text","label":"text2","req":0},'
. '{"type":"textarea","label":"Notes","req":1}]';
$b='[{"type":"textarea","label":"Notes","Element_Values":"331","Element_Name":"textarea-710091","Count_Images":0},'
. '{"type":"text","label":"text1","Element_Values":"1","Element_Name":"text-987351","Count_Images":0},'
. '{"type":"textarea","label":"Notes","Element_Values":"332","Element_Name":"textarea-254458","Count_Images":0},'
. '{"type":"text","label":"text2","Element_Values":"2","Element_Name":"text-3410","Count_Images":0},'
. '{"type":"textarea","label":"Notes","Element_Values":"333","Element_Name":"textarea-554051","Count_Images":0}]';
As you can see array 'a' starts with few keys which is not in array 'b'. I want to skip the arrays which has 'name' keys.
I did the following code, but didnt work:
$c = [];
$aJson=json_decode($a, true);
$bJson=json_decode($b, true);
foreach($aJson as $key => $array)
{
foreach($array as $an)
{
if(array_key_exists('name', $an))
{
//continue;
}
}
$c[$key] = array_merge($bJson[$key],$array);
}
echo json_encode($c);
The result array c should be:
[{"type":"textarea","label":"Notes","Element_Values":"331","Element_Name":"textarea-710091","Count_Images":0,"req":0},{"type":"text","label":"text1","Element_Values":"1","Element_Name":"text-987351","Count_Images":0,"req":0},{"type":"textarea","label":"Notes","Element_Values":"332","Element_Name":"textarea-254458","Count_Images":0,"req":0},{"type":"text","label":"text2","Element_Values":"2","Element_Name":"text-3410","Count_Images":0,"req":0},{"type":"textarea","label":"Notes","Element_Values":"333","Element_Name":"textarea-554051","Count_Images":0,"req":1}]
Please help me

This is a simple debug problem, $array is already the array.
$index = 0;
foreach($aJson as $key => $array)
{
if(isset($array['name']))
continue;
$c[$index] = array_merge($bJson[$index], $array);
$index++;
}

Related

How to return the array in recursive function in php

I'm trying to handle the recursive array in PHP. But my code is working fine. Problem is I'm unable to store the results in one array and return.
See the code:
function array_recursion(array $myarray, array $searchterms){
//empty array
$tempArr = array();
//loop through $myarray
foreach ($myarray as $key => $value){
if (is_array($value)){
array_recursion($value, $searchterms);
}
else if (in_array($key, $searchterms)){
print str_replace("0:", "", ($key . ": " . $value . "\n"));
}
}
}
//Call the function
$finalValue = array_recursion($arr, Array('VCHKEY','VOUCHERTYPENAME','VOUCHERNUMBER','PARTYNAME','NARRATION','REFERENCE','AMOUNT','VCHTYPE'));
//but this should print empty array
print_r($finalValue);die();
I want to use the below two lines in the above function
$tempArr[] = str_replace("0:", "", ($key . ": " . $value . "\n"));
return $tempArr;
What is the actual issue? Can anyone help to figure it out? Thanks in advance.
Finally i found the solution to return the value as array using recursion method.Check the below code.
function array_value_recursive(array $key, array $arr){
$val = array();
array_walk_recursive($arr, function($va, $ke) use($key, &$val){
if(in_array($ke,$key))
array_push($val, $va);
});
return count($val) > 1 ? $val : array_pop($val);
}
Hope this will help someone.

explode function return array with serial number

I have an array like this $arr = Array ("A","E","I","O","U");
My question is using implode function how can I make the output like this
1.A
2.E
3.I
4.O
5.U
You need to iterate over each values like this:
$arr = array("A","E","I","O","U");
foreach ($arr as $key => $value) {
echo $key + 1 . ".{$value} <br>";
}
This will give you the desired Output as:
1.A
2.E
3.I
4.O
5.U
Hope this helps!
$i = 1;
foreach ($arr as $v) {
echo $i . '.' . $v . '<br>';
$i++;
}
no need to use implode function. Just use foreach loop to iterate whole array.
use array_walk to traverse the array like this:
array_walk($array, function($v, $k)
{
echo $k + 1 . '.' . $v . "<br>";
});

replace any specific character in array key

$array['a:b']['c:d'] = 'test';
$array['a:b']['e:f']= 'abc';
I need output like below. array can have multiple level . Its comes with api so we do not know where colon come.
$array['ab']['cd'] = 'test';
$array['ab']['ef']= 'abc';
(untested code) but the idea should be correct if want to remove ':' from keys:
function clean_keys(&$array)
{
// it's bad to modify the array being iterated on, so we do this in 2 steps:
// find the affected keys first
// then move then in a second loop
$to_move = array();
forach($array as $key => $value) {
if (strpos($key, ':') >= 0) {
$target_key = str_replace(':','', $key);
if (array_key_exists($target_key, $array)) {
throw new Exception('Key conflict detected: ' . $key . ' -> ' . $target_key);
}
array_push($to_move, array(
"old_key" => $key,
"new_key" => $target_key
));
}
// recursive descent
if (is_array($value)) {
clean_keys($array[$key]);
}
}
foreach($to_move as $map) {
$array[$map["new_key"]] = $array[$map["old_key"]];
unset($array[$map["old_key"]]);
}
}
try this:
$array=array();
$array[str_replace(':','','a:b')][str_replace(':','','c:d')]="test";
print_r($array);
This seems like the simplest and most performant approach:
foreach ($array as $key => $val) {
$newArray[str_replace($search, $replace, $key)] = $val;
}

foreach doesn't print altered array properly

I am trying to print an array using foreach and while printing, if a certain $key comes up, I want to make changes to the array. Problem is, even though the array gets changed, the changes do not get printed.
In the example below, you will find:
function I use to change the array;
an array first printed with no changed;
then echo print-out in with changes during the process - all using foreach;
another print-out of the same table, but this time with changes.
<?php
function insert_before_key($array, $key, $data = NULL){
if (($offset = array_search($key, array_keys($array))) === false){
$offset = count($array);
}
return array_merge(array_slice($array, 0, $offset), (array) $data, array_slice($array, $offset));
}
$array = array(
"no_color" => "blank",
"color1" => "red",
"color2" => "green",
"color3" => "blue",
);
echo "<pre>";
print_r($array);
echo "</pre>";
foreach ($array as $key => $value) {
echo $key . ": " . $value . "<br />";
if ($key === "color1"){
$array = insert_before_key($array, "color2", array("color1.5" => "yellow"));
}
}
echo "<pre>";
print_r($array);
echo "</pre>";
echo "<br />";
?>
Note that the new $key is to jump in AFTER current $key, so I would expect it to come up.
Any idea why this happens ?
EDIT:
Played a bit more with foreach and I think it must be caching the keys or something...
<?php
$test_array = array(0,1,2,3,4,5,6,7,8,9);
foreach ($test_array as $key => $value) {
if ($key === 5){$test_array[7] = $test_array[7]+1;}
echo $key . ": " . $value . "<br />";
}
print_r($test_array);
?>
The above will display UNCHANGED echo, but CHANGED print_r.
From the manual: "As foreach relies on the internal array pointer, changing it within the loop may lead to unexpected behavior." http://php.net/manual/en/control-structures.foreach.php
You shouldn't modify an array you're looping over.
So during iteration you are trying to change the value of the item being iterated
foreach($array ...)
{
change $array
}
Use a copy of $array inside the iteration
$array2 = $array
foreach($array ...)
{
change $array2
}
I'd keep it simple. Something tells me however that you're fixing effects of a problem here and not its source.
$array = array(
"no_color" => "blank",
"color1" => "red",
"color2" => "green",
"color3" => "blue",
);
$temp_array = array();
foreach ($array as $key => $value) {
$temp_array[$key] = $value;
echo $key . ": " . $value . "<br />";
if ($key == 'color1') {
$key_add = 'color1.5';
$value_add = 'yellow';
$temp_array[$key_add] = $value_add;
echo $key_add . ": " . $value_add . "<br />";
}
}
$array = $temp_array;

PHP Merge Similar Objects In A Multidimensional Array

I have a multidimensional array in PHP, something that looks like:
array(array(Category => Video,
Value => 10.99),
array(Category => Video,
Value => 12.99),
array(Category => Music,
Value => 9.99)
)
and what I would like to do is combine similar categories and output everything into a table, so the output would end up being:
<tr><td>Video</td><td>23.98</td></tr>
<tr><td>Music</td><td>9.99</td></tr>
Any suggestions on how to do this?
EDIT:
I can have these in two different arrays if that would be easier.
A simple loop will do:
$array = [your array];
$result = array();
foreach ($array as $a) {
if (!isset($result[$a['Category']])) {
$result[$a['Category']] = $a['Value'];
} else {
$result[$a['Category']] += $a['Value'];
}
}
foreach ($result as $k => $v) {
echo '<tr><td>' . htmlspecialchars($k) . '</td><td>' . $v . '</td></tr>';
}
$result = array();
foreach ($array as $value) {
if (isset($result[$value['Category']])) {
$result[$value['Category']] += $value['Value'];
} else {
$result[$value['Category']] = $value['Value'];
}
}
foreach ($result as $category => $value) {
print "<tr><td>$category</td><td>$value</td></tr>";
}

Categories