Object JSON response using PHP - 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.

Related

How can I sort one array depending on another array?

I have two arrays stored in an array. They have the same number of values and are aligned:
$matrix['label1']
$matrix['label2']
I want to apply alphabetical sorting to $matrix['label1'] and move the contents of $matrix['label1'] in the same pattern. Here is an example of input and output.
$matrix['label1'] = ['b','c','a']
$matrix['label2'] = [ 1, 2, 3]
asort($matrix['label1'])
// outputs ['a','b','c']
//$matrix['label2'] should now be depending on that [ 3, 1, 2]
How can I change my asort() call to get this to work?
You are looking for array_multisort(), just pass both subArrays as arguments to it:
<?php
$matrix['label1'] = ['b','c','a'];
$matrix['label2'] = [ 1, 2, 3];
array_multisort($matrix['label1'], $matrix['label2']);
print_r($matrix);
?>
output:
Array
(
[label1] => Array
(
[0] => a
[1] => b
[2] => c
)
[label2] => Array
(
[0] => 3
[1] => 1
[2] => 2
)
)

Passing multiple arrays to a Cartesian function

I need to pass multiple array's in an indexed format to a cartesain function in order to calculate every permutation. This works when the code is:
$count = cartesian(
Array("GH20"),
Array(1,3),
Array(6,7,8),
Array(9,10)
);
I will not always know the length, number of arrays, or values so they are stored in another array "$total" which may look something like this:
Array (
[0] => Array
(
[0] => 1
[1] => 3
)
[1] => Array
(
[0] => 6
[1] => 7
[2] => 8
)
[2] => Array
(
[0] => 9
[1] => 10
)
)
I have tried implementing the user_call_back_function as per:
$count = call_user_func('cartesian', array($total));
However the array that then gets passed looks like this:
Array (
[0] => Array (
[0] => Array (
[0] => Array (
[0] => 1
[1] => 3
[2] => 4
)
[1] => Array (
[0] => 5
[1] => 6
[2] => 7
[3] => 8
)
[2] => Array (
[0] => 9
[1] => 10
)
)
)
)
Where am I going wrong, why is the array being buried further down in dimensions where it is not needed, and is this the reason why my cartesain function does no longer work?
Thanks, Nick
As requested, here is my cartesain function:
function cartesian() {
$_ = func_get_args();
if(count($_) == 0)
return array(array());
$a = array_shift($_);
$c = call_user_func_array(__FUNCTION__, $_);
$r = array();
foreach($a as $v)
foreach($c as $p)
$r[] = array_merge(array($v), $p);
return $r;
}
why is the array being buried further down in dimensions where it is not needed?
Simply because you are wrapping an array in another array when calling call_user_func.
$count = call_user_func('cartesian', array($total));
Perhaps you meant this:
$count = call_user_func('cartesian', $total);
is this the reason why my cartesain function does no longer work?
I don't know, you have not posted your cartesain, just an arrat called cartesain
EDIT as op updated the question.
If you are using PHP 5.6 you should be able to use the splat operator.
call_user_func("cartesain", ...$total);
Disclaimer, I have not tested this.
Arrays and Traversable objects can be unpacked into argument lists when calling functions by using the ... operator.

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

php - remove indexes of an aray if they have the same value

How can i make the values of such an array unique.
Array ( [0] => Array ( [0] => wallet [1] => pen [2] => perfume [3] => pen) )
as there is pen twice i would like it to be deleted in this way :
( [0] => Array ( [0] => wallet [1] => pen [2] => perfume) )
OR
( [0] => Array ( [0] => wallet [1] => perfume [2] => pen) )
and i would like it to apply for any length.
thanks for your help
How about array_flip used twice:
$arr = Array(0 => wallet, 1 => pen, 2 => perfume, 3 => pen);
$arr = array_flip(array_flip($arr));
print_r($arr);
output:
Array
(
[0] => wallet
[3] => pen
[2] => perfume
)
If you want to renumbered the indexes, add this ligne after:
$arr = array_values($arr);
if you just want to select a unique value you need to pass the array that you want to compare the values, I am assuming you passed the main array, you need to pass the array where the problem is found which is in your case the index 0 of an array
$result = array_unique($input[0]);
$input will have an array of unique values so pen will not be 2
if you need to delete any duplicated values in the array you can do this.
$input[0] = array_unique($input[0]);
if you need to reset the index you can use this
$new_index = array_values($input[0]);
print_r($new_index);
$tmp = array ();
foreach ($array as $row)
array_push($tmp,array_unique($row));
Here is the solution for multi dimensopnal array
$res = array();
foreach($your_array as $key=>$val){
$res[$key] = array_unique($val);
}
echo "<pre>";
print_r($res);

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