How to remove array index from a json_encode php [duplicate] - php

This question already has answers here:
How do I encode a PHP array to a JSON array, not object?
(4 answers)
Closed 8 years ago.
I'm trying to remove numbers that is being display in my json 2d array. I first had an 2d array that is dynamic and deletes elements from that array. Then it converts the array to a json 2d array. The problem is I don't want the numbers at the start.
Like below
[
"1": {"StateName":"Alaska","StateAbbr":"AK"},
"2": {"StateName":"Alabama","StateAbbr":"AL"},
"3": {"StateName":"Arkansas","StateAbbr":"AR"},
"4": {"StateName":"Arizona","StateAbbr":"AZ"},
"5": {"StateName":"California","StateAbbr":"CA"},
"6": {"StateName":"Colorado","StateAbbr":"CO"},
"7": {"StateName":"Connecticut","StateAbbr":"CT"}
]
I would like it to be like this
[
{"StateName":"Alaska","StateAbbr":"AK"},
{"StateName":"Alabama","StateAbbr":"AL"},
{"StateName":"Arkansas","StateAbbr":"AR"},
{"StateName":"Arizona","StateAbbr":"AZ"},
{"StateName":"California","StateAbbr":"CA"},
{"StateName":"Colorado","StateAbbr":"CO"},
{"StateName":"Connecticut","StateAbbr":"CT"}
]
With out the numbers. How can I do this?
I tried mysql_fetch_assoc but it doesn't work it.
$arr = array();
while($row = mysql_fetch_assoc($result)) {
$arr[] = $row;
}
echo json_encode($arr);

I found out how to remove the keys from the 2d array once converted to a json. Create functions to do this.
function remove_json_keys($array) {
foreach ($array as $k => $v) {
if (is_array($v)) {
$array[$k] = $this->remove_json_keys($v);
} //if
} //foreach
return $this->sort_numeric_keys($array);
}
function sort_numeric_keys($array) {
$i=0;
foreach($array as $k => $v) {
if(is_int($k)) {
$rtn[$i] = $v;
$i++;
} else {
$rtn[$k] = $v;
} //if
} //foreach
return $rtn;
}

Related

How can I concatenate and print only values from json object after calling json_decode in php?

This is a schema generator that displays the key:value pair
"default": [
{
"one": "u0001u0000u0000u0000",
"two": "u0002u0000u0000u0000",
"three": "u0003u0000u0000u0000"
}
]
What I would like to print out is "default": [{"u0001u0000u0000u0000u0002u0000u0000u0000u0003u0000u0000u0000"}]
Similarly if it is an object for instance:
"default": [ "a":
{
"one": "u0001u0000u0000u0000",
"two": "u0002u0000u0000u0000",
"three": "u0003u0000u0000u0000"
}
]
concatenate only values and print like this:
["a": {"u0001u0000u0000u0000u0002u0000u0000u0000u0003u0000u0000u0000"}]
Sample Code Test:
// this method gets the value entered by user in json format. The user can put in a nested json format as well. The above examples that I mentioned works.
it then calls for scanForNestedType method which scans whether the format contains any array, array>, map etc...
Once it scans for nested type, it internally calls $this->encodeValues($unit)which converts the values entered by user from integer to bytes.
Here is an example:
User enters array
[{"one": 1, "two": 2, "three": 3}]. After conversion, the result would be as follows:
[
{
"one": u0001u0000u0000u0000,
"two": u00002u0000u0000u0000,
"three: u0003u0000u0000u0000
}
]
Now I am getting the values correctly for each key. All I need is to print in this format:
[
{
u0001u0000u0000u0000u0002u0000u0000u0000u0003u0000u0000u0000
}
]
private function jsonDecode(array $value)
{
$strValue = $value['value'];
$jsonValue = json_decode($strValue);
$this->scanForNestedType($jsonValue);
return $jsonValue;
}
private function scanForNestedType(&$value)
{
foreach ($value as $key => &$unit) {
if (is_array($unit) || is_object($unit)) {
$this->scanForNestedType($unit);
} else {
$value->$key = $this->encodeValues($unit);
}
}
}
private function encodeValues(int $value)
{
$encodedValue = '';
$bytesArray = unpack("C*", pack("V", $value));
foreach ($bytesArray as $byte) {
$encodedValue .= sprintf('u%04x', dechex($byte));
}
return $encodedValue;
}
If I get a working example then it would be great!
You can use json_decode to convert json to an array. Then implode sub-array ['one'....] using foreach loop.
snippet
$json1 = '[{"one": "u0001u0000u0000u0000", "two": "u0002u0000u0000u0000", "three": "u0003u0000u0000u0000"}]';
$json2 = '[{ "a": { "one": "u0001u0000u0000u0000", "two": "u0002u0000u0000u0000", "three": "u0003u0000u0000u0000" } }]';
$arr1 = json_decode($json1,true);
$arr2 = json_decode($json2,true);
foreach($arr1 as $data){
$default1[] = implode($data);
}
$default1 = json_encode($default1, JSON_FORCE_OBJECT);
foreach($arr2 as $key => $child){
foreach($child as $childKey => $data){
$default2[$childKey] = implode($data);
}
}
$default2 = json_encode($default2, JSON_FORCE_OBJECT);
print_r($default1);
print_r($default2);
Output
{"0":"u0001u0000u0000u0000u0002u0000u0000u0000u0003u0000u0000u0000"}
{"a":"u0001u0000u0000u0000u0002u0000u0000u0000u0003u0000u0000u0000"}
Live Demo
You can now json_decode $default1, $default2 to get php object/array.

How to Replace One Array index with another array in Php [duplicate]

This question already has answers here:
PHP array replace after matching value [duplicate]
(2 answers)
Closed 2 months ago.
Am using Php as my serverside scripting language.In my project I used Json string decoded into array.
My problem is how to overwrite the existing array index based on an array value.
my existing array looks like :
$array1 =[
{
"Name":"apple",
"color":"red",
"property":[
{
"p1":"value1",
"p2":"value2"
}
]
},
{
"Name":"Grape",
"color":"violet",
"property":[
{
"p1":"value1",
"p2":"value2"
}
]
}
];
and the updated array content looks:
$upadatearray = [
{
"Name":"apple",
"color":"green",
"property":[
{
"p1":"newvalue",
"p2":"newvalue2"
}
]
}
];
I want to update the existing $array1 with new $upadatearray , bsed on the "Name" .If it is same then replace.
I want to look like:
$finalarray =[
{
"Name":"apple",
"color":"green",
"property":[
{
"p1":"newvalue",
"p2":"newvalue2"
}
]
},
{
"Name":"Grape",
"color":"violet",
"property":
[
{
"p1":"value1",
"p2":"value2"
}
]
}
];
I tried this :
for($j=0;$j<count($array1);$j++)
{
if($array1[$j]['Name'] == $upadatearray[0]['Name'])
$finalarray = array_replace($array1[$j],$upadatearray[0]);
}
But it will not work correctly.Is there any possible solution ?
Let you have this two arrays:
$array1 ='[{"Name":"apple","color":"red","property":[{"p1":"value1","p2":"value2"}]},{"Name":"Grape","color":"violet","property":[{"p1":"value1","p2":"value2"}]}]';
$upadatearray = '[{"Name":"apple", "color":"green", "property":[{"p1":"newvalue","p2":"newvalue2"}]}]';
$array1 = json_decode($array1, true);
$upadatearray = json_decode($upadatearray, true);
You can use array_replace function. But to make it replace items based on the Name column you should first make this column a key of array
function make_column_key($arr, $col_name) {
$keys = array_column($arr, $col_name);
$result = array_combine($keys, $arr);
return $result;
}
$array1 = make_column_key($array1, 'Name');
$upadatearray = make_column_key($upadatearray, 'Name');
And now simply use array_replace
$finalarray = array_replace($array1, $upadatearray);
If you don't need Name be the key of final array, you can get only values:
$finalarray = array_values($finalarray);
hi I think this code will help you.
//what i did is i created a final array variable which gets the value of old array.
$finalArray = $array1;
//then i perform a foreach loop for old array
foreach ($array1 as $key => $oldarray) {
//inside the updated array
foreach ($upadatearray as $key => $newarray) {
//if old array name and new array name is same replace content on the final array
if ($oldarray['Name'] == $newarray['Name']) {
$finalArray['Name'] = $newarray['Name'];
}
}
}

Remove object from array - object is returned instead of array

I'm looping through an array of $students and removing those that are already in the $enrolled array.
$i=0;
foreach($students as $student)
{
foreach($enrolled as $enrollment)
{
if ($enrollment->id == $student->id)
{
unset($students[$i]);
}
}
$i++;
}
return Response::json(array(
'available' => $students
));
That leaves me with the following output:
"available": {
"2": {
"id": "4"
"user_id": "4",
"teacher_id": null,
"parent_id": "4",
"active": "1"
}
}
What I'm trying to achieve is that available is an array, holding that one student. What am I doing wrong here?
Javascript arrays are zero-indexed so you cannot have an array with one element and an index that is not zero.
To get that from your php array, you need to re-index it before you encode it:
// re-index the array
$students = array_values($students);
return Response::json(array(
'available' => $students
));
See a simple example here.
for($i = 0; $i < count($students); $i++)
{
$student = $students[$i];
foreach($enrolled as $enrollment)
{
if ($enrollment->id == $student->id)
{
unset($students[$i]);
}
}
}
return Response::json(array(
'available' => array_values($students)
));
don't use foreach and unset on the same element, better would be for, because unset causes some problems to foreach if you think about it how foreach works (iterators, keys, whatever)

foreach variable equal to another variable

I want to foreach $key equal to $values to return the $called that matches the $key.
foreach($value as $values);
foreach($json['values'] as $key => $called) {
if($key == $values) {
$myreturns[] = $called;
}
}
return json_encode($myreturns, true);
I have a select multiple which value is a number and if not a number on registration it fails (to stop people changing values).
I populate it with the following json
{
"values": {
"1": "Black",
"2": "Blue",
"3": "Brown",
"4": "Grey",
"5": "Green",
"6": "Hazel",
"7": "Violet"
}
}
if somebody chose black and blue, the values will be 1 and 2.
For example I want foreach $key so the json above if that number is equal to "1" to return the $called that is related to the $key.
I know this is wrong but I want something like this
foreach($key == $values) {
$myreturns[] = $called;
}
Close. use array_push to push the results into a new array, then json encode that.
// json decode into associative array
$values = json_decode($json, true);
// init results
$results = array();
foreach($values as $key => $value) {
if($called == $key) {
array_push($results,$value);
}
}
$result = json_encode($result);
return $result;
Also note that if you want to get an item within a json array, it is easier to just reference it within the array:
$array = json_decode($json,true);
$item = $array[$key];

Searching for duplicates in multidimensional array PHP

I have a multidimensional PHP array looking like this in JSON:
array = [{
"id":"1",
"key":"Ferrari",
"type":"car"},
{
"id":"1",
"key":"Red",
"type":"color"},
{
"id":"73",
"key":"Yellow",
"type":"color"
}]
Because it's actually a search result, I would like to, dynamically combine the results where the id's are the same. In other words the new array should look like:
array = [{
"id":"1",
"key":"Red Ferrari",
"type":"keyword"},
{
"id":"73",
"key":"Yellow",
"type":"color"
}]
I have been looking at a lot of PHP functions, but they have a limited functionality, in multidimensional arrays. Any suggestions are appreciated :)
Many Regards
Andreas
There's no base functions to do as specific thing as you mention. So you can make something like this:
print_r(my_array_merge($data));
function my_array_merge($data)
{
// sort all records by id to merge them later
$data_by_id = array();
foreach ($data as $item)
{
if (!isset($data_by_id[ $item['id'] ])) {
$data_by_id[ $item['id'] ] = array();
}
$data_by_id[ $item['id'] ][] = $item;
}
// merge records with same id
$return = array();
foreach ($data_by_id as $id => $items)
{
foreach ($items as $item)
{
if (!isset($return[ $id ])) {
$return[ $id ] = $item;
} else {
$return[ $id ]['key'] .= ' ' . $item['key'];
$return[ $id ]['type'] = 'keyword'; // I don't really get what you mean by 'keyword'
}
}
}
// reset keys before return
return array_values($return);
}

Categories