array_push the first key of an array - php

I'm having a hard time adding a piece to an array in an if statement while using array_push. If I try to change $arr to $arr[0], then I get an error :
Notice: Undefined offset: 0
PHP:
$data = array('test' => 'value');
if(!empty($_POST['stuff'])){
$arr = array('test2' => array(array('test3' => 'value')));
array_push($data, $arr);
}
$data_string = json_encode($data, JSON_PRETTY_PRINT);
this is what's currently happening:
{
"test": "value",
"0": {
"test2": [{
"test3": "value"
}]
}
}
This is what I want to happen:
{
"test": "value",
"test2": [{
"test3": "value"
}]
}

Use array_merge() instead :
$data = array_merge($data,$arr);
Example

Don't use array_push, you can't control associative keys:
$data['test2'] = array(array('test3' => 'value'));

array_push is for indexed arrays. You are using an associative array and so you simply need to do
$data = array('test' => 'value');
if(!empty($_POST['stuff'])){
$data['test2'] = array(array('test3' => 'value')));
}

Related

Check if value is in array using 2 specific keys

I have an array like this:
$arr = ({
"ID":"10",
"date":"04\/22\/20"
},
{
"ID":"20",
"date":"05\/25\/20"
},
{
"ID":"32",
"date":"07\/13\/20"
});
I want to know if values on 2 different keys exist in the array, how can I Achieve that?
Example: if id is equal to 32 and date equals to 07/13/20, return true.
I've tried in_array($monthName, array_column($GLOBALS['group_posts_array'], 'month')); but this only works on one key. I want to achieve to keys at once, kind of like && in if statement.
I don't think $arr in the question is a valid php array, but if it should be a multidimensional array, you might also pass for example an array to in_array with the keys and values that you are looking for:
$arr = [
[
"ID" => "10",
"date" => "04\/22\/20"
],
[
"ID" => "20",
"date" => "05\/25\/20"
],
[
"ID" => "32",
"date" => "07\/13\/20"
]
];
$values = [
"ID" => "32",
"date" => "07\/13\/20"
];
var_dump(in_array($values, $arr, true));
$values["ID"] = "33";
var_dump(in_array($values, $arr, true));
Output
bool(true)
bool(false)
You can implement a 'some' function.
function some(array $arr, callable $fn):bool{
foreach($arr as $index=>$item){
if($fn($item, $index)){
return true;
}
}
return false;
}
The usage would be something like the following:
$id = 32;
$date = "07/13/20";
$isInArray = some($arr, function($item, $index) use ($id, $date){
return $item->id == $id && $item->date == $date;
})

How to convert a PHP array into json string

I have a PHP array built with a while loop. I do successfully convert it to JSON string, however the output is not what I want and need some help to get it right:
My current code:
while(!$sql_query->EOF){
$data[] = array(
'id' => $id,
'name' => $name,
'title' => $title
);
$sql_query-> MoveNext(); }
echo json_encode($data);
The output I get with my code is this:
[
{
"id":"1",
"name":"Nick",
"title":"Office"
},
{
"id":"2",
"name":"Amy",
"title":"Home"
}
]
However, I need the outcome to be:
{
"data": [
[
"1",
"Nick",
"Office"
],
[
"2",
"Amy",
"Home"
]
]
}
I tired paying around with array_values() but no success so far.
Can somebody suggest the right approach here?
When building your array, don't add the keys to the values, this will allow the encoding to use array notation, then add the "data" key as part of the encode...
$data = [];
while(!$sql_query->EOF){
$data[] = [ $id, $name,$title];
$sql_query-> MoveNext();
}
echo json_encode(["data" => $data]);
If you do something like:
$result = (object)["data" => $data];
echo json_encode($data);
this will give you the output you require.
First of all you have to modify you array
$newData = [];
foreach($data as $item) {
$newData[] = array_values($item);
}
and then create new array
echo json_encode(["data"=>$newData])

How to extract perticular array value from multidimentional array

How can I get the list of all ids from the array given below,
$filteredZips=[{
"id": 21,
"distance": "0"
},
{
"id": 20,
"distance": "3.9399923305414037"
},
{
"id": 29,
"distance": "8.33045537474091"
}]
Expected result will be :
$id = array('21','20','29');
There is a function called array_column that will grab one column in an array.
First the string needs to be converted to array with Json_decode and second parameter to true.
Then array_column returns your expected output.
No looping is needed.
$filteredZips='[{
"id": 21,
"distance": "0"},{
"id": 20,
"distance": "3.9399923305414037"},{
"id": 29,
"distance": "8.33045537474091"}]';
$filteredZipsarr = json_decode($filteredZips,true);
$id = array_column($filteredZipsarr, "id");
Var_dump($id);
https://3v4l.org/hFOKR
If you don't need the $filteredZipsarr you can make it a one liner:
$id = array_column(json_decode($filteredZips,true), "id");
Use array_map function:
$id = array_map(function($value){
return $value['id'];
}, $filteredZips);
Documentation: http://php.net/manual/en/function.array-map.php
First you need to decode JSON string to access it as Array of Objects :
$filteredZips = json_decode($filteredZips);
$results = array();
foreach ($filteredZips as $zip) {
$results[] = $zip->id;
}
print_r($results);
Check here : https://3v4l.org/kfkhV
Use array_column after transform your JSON with json_decode
$ids = array_column(json_decode($filteredZips, true), 'id');
Array
(
[0] => 21
[1] => 20
[2] => 29
)
Solution:
$answer = [];
foreach($filteredZips as $array){
if(isset($array['id'])){
$answer[]=$array['id'];
}
}
var_dump($answer);
Try this:
$ids = array();
foreach ($filteredZips as $zip) {
$ids[] = $zip["id"];
}
var_dump($ids);
Dont forget to use json_decode function to get a proper php array.

How to Create Nested JSon With php

How do I create a JSON like this with PHP? I am trying to convert a dynamic data and save it into a MySQL database.
{
"fbd49440-a5a1-48be-b13e-e8efddad3588": {
"0": {
"value": "dsfrasdf5464356dfs hdhfg dfgh"
}
},
"0fc71cea-5609-40a7-a1d2-b78139660f8f": {
"0": {
"value": "50"
}
},
"73936e70-4329-4aba-b47c-42c64ced420c": {
"0": {
"file": "\/components\/com_djclassifieds\/images\/item\/25_juliet_ibrahim.jpg",
"uniqid": "59a352b96773325",
"title": "",
"file2": "",
"overlay_effect": "",
"caption": "",
"width": "",
"height": ""
},
"ac00b95e-9eeb-4035-bf4a-ff206319b2d6": {
"0": {
"value": "members-in-good-standing-2014",
"text": "",
"target": "0",
"custom_title": "",
"rel": ""
}
},
"69072346-fe4c-489e-8e2b-5a7d7409fd44": {
"0": {
"value": "34"
}
}
}
I tried the code below but it did not give me the result I want.
$json = (
"fbd49440-a5a1-48be-b13e-e8efddad3588"=> (
$array1
),
"0fc71cea-5609-40a7-a1d2-b78139660f8f"=> (
$array2
),
"73936e70-4329-4aba-b47c-42c64ced420c"=> (
$array3
),
"ac00b95e-9eeb-4035-bf4a-ff206319b2d6"=> (
$array4
),
"69072346-fe4c-489e-8e2b-5a7d7409fd44"=> (
$array5
)
)
echo json_encode($json);
I will be glad if someone could help me, thank you
json_encode will take multiple types of valid data and try to encode them into a json representation of it. It does require that the input is valid.
The code you have pasted has multiple syntax errors, and we cannot tell what is in your $array1. $array2, $array3, $array4, $array5. However a couple of changes (and assuming your $arrays are actual arrays) has your code working.
There are also bitmask options in the form of JSON Constants that will define how your JSON should be stored.
$array = array( "data" => "value"); // dummy array to show data working
$json = array( //defined the following as an array
"fbd49440-a5a1-48be-b13e-e8efddad3588"=> array( //notice each of these are now defined as arrays
$array
),
"0fc71cea-5609-40a7-a1d2-b78139660f8f"=> array(
$array
),
"73936e70-4329-4aba-b47c-42c64ced420c"=> array(
$array
),
"ac00b95e-9eeb-4035-bf4a-ff206319b2d6"=> array(
$array
),
"69072346-fe4c-489e-8e2b-5a7d7409fd44"=> array(
$array
)
); //added semicolon to end the declaration
echo json_encode($json, ( JSON_FORCE_OBJECT + JSON_PRETTY_PRINT ) );
// added JSON_FORCE_OBJECT and JSON_PRETTY_PRINT
// As bitmask options, they return a constant to give `json_encode` instructions
// JSON_FORCE_OBJECT => 16, JSON_PRETTY_PRINT => 128
// JSON_FORCE_OBJECT + JSON_PRETTY_PRINT = 16 + 128 = 144
// json_encode( $array, ( JSON_FORCE_OBJECT + JSON_PRETTY_PRINT ) = json_encode ($array, 144);
Returns
{"fbd49440-a5a1-48be-b13e-e8efddad3588":{"0":{"data":"value"}},"0fc71cea-5609-40a7-a1d2-b78139660f8f":{"0":{"data":"value"}},"73936e70-4329-4aba-b47c-42c64ced420c":{"0":{"data":"value"}},"ac00b95e-9eeb-4035-bf4a-ff206319b2d6":{"0":{"data":"value"}},"69072346-fe4c-489e-8e2b-5a7d7409fd44":{"0":{"data":"value"}}}
Array of Arrays in your json data.
If you want it to print the index of each result, that needs to be treated as an array as well. Simple enough to understand when there are multiple pairs in the result, less intuative when the result is one pair.
$array1 = array( "data" => "value");
echo json_encode($array1, JSON_FORCE_OBJECT );
//would return
//{"data":"value"}
$array2 = array(
array( "data" => "value" ),
array( "data" => "value" )
);
echo json_encode($array2, JSON_FORCE_OBJECT );
// would return
// {"0":{"data":"value"},"1":{"data":"value"}}
$array3 = array(
array( "data" => "value" )
);
echo json_encode($array3, JSON_FORCE_OBJECT );
// would return
// {"0":{"data":"value"}}

How to show JSON data with Associate Array Key?

in the below code, i used simple $key,$value but i want to use that code with associate array key. Then how can i do? Please help.
<?php
function custom_table_page_display() {
$jsonData = '{ "User":"John", "Age":22, "Country":"India" }';
$phpArray = json_decode($jsonData);
$rows = array();
foreach($phpArray as $key => $value)
{
$rows[] = $key;
$value1[]=$value;
}
$header=$rows;
$value11[]=$value1;
$output = theme('table',array('header'=>$header,'rows' => $value11));
return $output;
}
?>
You need to use
$phpArray = json_decode($jsonData, true);
The second argument says whether to return an associative array or object for a JSON object. By default it returns an object.
You can replace your foreach loop with:
$rows = array_keys($phpArray);
$value1 = array_values($phpArray);
For the data you gave in the comment below, you would do:
$rows = array_keys($phpArray['Class'][0]);
$values = array_map('array_values', $phpArray['Class']);
$values will then be a 2-dimensional array of values:
[ [ "John", 22, "India" ],
[ "Sam", 23, "Argentina" ],
[ "John", 22, "Algeria" ]
]
DEMO

Categories