Here a have a json string, and need to get all the parent array positions of registratition_id
E.g. i want the array at the end to out put something like this:
[0] =>0
[1] =>1
[2] =>3
In fact I want to get all the arrays position which contain registration_id
$json_raw = '{"multicast_id":6446899316497614986,
"success":5,
"failure":1,
"canonical_ids":3,
"results":[
{"registration_id":"APA91bEgLFvrc0lnXqX3C1euQohdHrv_wbxtGP86ezRzGWEVMQPpJjw1GMhGzfkI8Q34TU1KRts2j_-7CyU4ce6MlX5DB3umpXDGl-Ebmg53b44UKga79ee9Sal6gT_9rP3KIz9pDEUk2JVJsQmxiWXWoIfrYEAmFg",
"message_id":"0:1396175384218906%50b5570df9fd7ecd"
},
{"registration_id":"APA91bEgLFvrc0lnXqX3C1euQohdHrv_wbxtGP86ezRzGWEVMQPpJjw1GMhGzfkI8Q34TU1KRts2j_-7CyU4ce6MlX5DB3umpXDGl-Ebmg53b44UKga79ee9Sal6gT_9rP3KIz9pDEUk2JVJsQmxiWXWoIfrYEAmFg",
"message_id":"0:1396175384218155%50b5570df9fd7ecd"
},
{"message_id":"0:1396175384218718%b91f4d1ff9fd7ecd"
},
{"registration_id":"APA91bEgLFvrc0lnXqX3C1euQohdHrv_wbxtGP86ezRzGWEVMQPpJjw1GMhGzfkI8Q34TU1KRts2j_-7CyU4ce6MlX5DB3umpXDGl-Ebmg53b44UKga79ee9Sal6gT_9rP3KIz9pDEUk2JVJsQmxiWXWoIfrYEAmFg",
"message_id":"0:1396175384219100%50b5570df9fd7ecd"
},
{"message_id":"0:1396175384219927%50b5570df9fd7ecd"
},
{"error":"InvalidRegistration"
}]
}';
Use a foreach loop and check if registration_id isset
$obj = json_decode($json_raw);
$resultsWithRegID = array();
foreach($obj->results as $index=>$element){
if(isset($element->registration_id)){
$resultsWithRegID[] = $index;
}
}
Just an alternative version:
$array_raw = json_decode($json_raw, true);
$what = "registration_id";
$res = array_keys(array_filter($array_raw['results'], function($item) use ($what)
{
return isset($item[$what]);
}));
var_dump($res);
Obviously you can:
define the key to search straight inside the isset($item["registration_id"])
omit the wrapping function array_keys if you need the whole part of the array filtered
(whole part)
array (size=3)
0 =>
array (size=2)
'registration_id' => 'APA91bEgLFvrc0lnXqX3C1euQohdHrv...'
'message_id' => ''
1 =>
array (size=2)
'registration_id' => 'APA91bEgLFvrc0lnXqX3C1euQohdHrv...'
'message_id' => '0:1396175384218155%50b5570df9fd7ecd'
3 =>
array (size=2)
'registration_id' => 'APA91bEgLFvrc0lnXqX3C1euQohdHrv...'
'message_id' => '0:1396175384219100%50b5570df9fd7ecd'
<html>
<head>
<title>Online PHP Script Execution</title>
</head>
<body>
<?php
$json_raw = '{"multicast_id":6446899316497614986,
"success":5,
"failure":1,
"canonical_ids":3,
"results":[
{"registration_id":"APA91bEgLFvrc0lnXqX3C1euQohdHrv_wbxtGP86ezRzGWEVMQPpJjw1GMhGzfkI8Q34TU1KRts2j_-7CyU4ce6MlX5DB3umpXDGl-Ebmg53b44UKga79ee9Sal6gT_9rP3KIz9pDEUk2JVJsQmxiWXWoIfrYEAmFg",
"message_id":"0:1396175384218906%50b5570df9fd7ecd"
},
{"registration_id":"APA91bEgLFvrc0lnXqX3C1euQohdHrv_wbxtGP86ezRzGWEVMQPpJjw1GMhGzfkI8Q34TU1KRts2j_-7CyU4ce6MlX5DB3umpXDGl-Ebmg53b44UKga79ee9Sal6gT_9rP3KIz9pDEUk2JVJsQmxiWXWoIfrYEAmFg",
"message_id":"0:1396175384218155%50b5570df9fd7ecd"
},
{"message_id":"0:1396175384218718%b91f4d1ff9fd7ecd"
},
{"registration_id":"APA91bEgLFvrc0lnXqX3C1euQohdHrv_wbxtGP86ezRzGWEVMQPpJjw1GMhGzfkI8Q34TU1KRts2j_-7CyU4ce6MlX5DB3umpXDGl-Ebmg53b44UKga79ee9Sal6gT_9rP3KIz9pDEUk2JVJsQmxiWXWoIfrYEAmFg",
"message_id":"0:1396175384219100%50b5570df9fd7ecd"
},
{"message_id":"0:1396175384219927%50b5570df9fd7ecd"
},
{"error":"InvalidRegistration"
}]
}';
$data=json_decode ($json_raw);
$arr= $data->{'results'};
$i=0;
$n_r=array();
foreach($arr as $d)
{$n_r[]=$arr[$i]->{'registration_id'};
$i=$i+1;}
print_r($n_r);
?>
</body>
</html>
Convert JSON to Array - Rest is yours:
$array = json_decode($json_raw, true);
// results with registration_id
$results = array();
foreach($array['results'] as $index => $element) {
if(isset($element['registration_id']) === true) {
$results[] = $index;
}
}
var_dump($results);
Related
I have this function, where a array_filter function is included:
$var = "test";
function mainFunction() {
global $var;
$myNewArray = array();
$data = array("a", "b", "c");
array_filter($data, function ($value) {
global $myNewArray;
$myNewArray[] = $value;
});
print_r($myNewArray); // TEST OUTPUT
}
mainFunction();
Problem:
My test output myNewArray is empty.
I know that my array_filter function is senless at the moment until I check no values.
But only for testing, I would like to use it, to create a newArray. But this doesn't work. Where is my mistake?
UPDATE
I updated my code:
function mainFunction() {
global $var;
$myNewArray = array();
$data[] = array("id" => "1", "content" => "Hello");
$data[] = array("id" => "2", "content" => "World");
$myNewArray = array_filter($data, function ($value) {
if ($value['content'] == "World") {
return $value['content'];
}
});
print_r($myNewArray); // TEST OUTPUT
}
mainFunction();
This works, but not correctly.
I would like to save only the content value.
But my $myNewArray looks like this:
Array
(
[0] => Array
(
[id] => 2
[content] => World
)
)
Instead of
Array
(
[0] => Array
(
[content] => World
)
)
I would combine array_filter and array_map for this.
$data[] = array("id" => "1", "content" => "Hello");
$data[] = array("id" => "2", "content" => "World");
// filter the data
$data = array_filter($data, fn ($value) => $value['content'] === 'World');
// map the data
$data = array_map(fn ($value) => ['content' => $value['content']], $data);
// reset indexes
$data = array_values($data);
print_r($data);
Example: https://phpize.online/s/9U
Everything seems to work fine.
<?php
$data = [];
$data[] = array("id" => "1", "content" => "Hello");
$data[] = array("id" => "2", "content" => "World");
$filtered_data = array_filter($data, function($value) {
return $value['content'] == "World";
});
print_r($filtered_data);
The output is just like expected:
Array (
[1] => Array
(
[id] => 2
[content] => World
)
)
But if you want to leave only some fields in resulting array, array_filter will not help you (at least without a crutch).
You may want to iterate source array and filter it by yourself.
<?php
$data = [];
$data[] = array("id" => "1", "content" => "Hello");
$data[] = array("id" => "2", "content" => "World");
$filtered_data = [];
foreach($data as $v) {
if($v['content'] == "World")
$filtered_data[] = ["content" => $v['content']];
}
print_r($filtered_data);
The output then would be:
Array (
[0] => Array
(
[content] => World
)
)
You want two different things :
filter your array (keep only some elements)
map your array (change the value of each element)
Filter your array
On your second attempt you've done it right but array_filter callback function expect a boolean as the return value. It will determine wherever array_filter need to keep the value or not.
Map your array
You need to remove all value on each element except the "content" value. You can use array_map to do that.
function mainFunction() {
$data[] = array("id" => "1", "content" => "Hello");
$data[] = array("id" => "2", "content" => "World");
$myNewArray = array_filter($data, function ($value) {
if ($value['content'] == 'World') {
return true;
}
return false;
});
// myNewArray contains now the willing elements, but still don't have the willing format
/* myNewArray is [
0 => [
'id' => '2',
'content' => 'World'
]
]*/
$myNewArray = array_map($myNewArray, function($value){
return [
'content' => $value['content']
];
});
// myNewArray contains now the willing elements with the willing format
/* myNewArray is [
0 => [
'content' => 'World'
]
] */
}
mainFunction();
In mainFunction you are not using $myNewArray as global so it's only in the scope, but in the array_filter function you are using global $myNewArray;
$var = "test";
$myNewArray; // global array
function mainFunction() {
global $var, $myNewArray;//if this is not present it's not global $myNewArray
$myNewArray = array();
$data = array("a", "b", "c");
array_filter($data, function ($value) {
global $myNewArray;//this uses global
$myNewArray[] = $value;
});
print_r($myNewArray); // TEST OUTPUT
}
mainFunction();
Here is an example of you code without global $myNewArray
$var = "test";
function mainFunction($var) {
$myNewArray = array();
$data = array("a", "b", "c");
$myNewArray[] = array_filter($data, function ($value) {
return $value;
});
print_r($myNewArray); // TEST OUTPUT
}
mainFunction($var);
Answer to Update:
You can use array_reduce to achieve that
function mainFunction() {
global $var;
$myNewArray = array();
$data[] = array("id" => "1", "content" => "Hello");
$data[] = array("id" => "2", "content" => "World");
$myNewArray = array_reduce($data, function($accumulator, $item) {
if ($item['content'] === "World")
$accumulator[] = ['content' => $item['content']];
return $accumulator;
});
print_r($myNewArray); // TEST OUTPUT
}
mainFunction();
you can use this code..........
<?php
function test_odd($var)
{
return($var & 1);
}
$a1=array(1,3,2,3,4);
print_r(array_filter($a1,"test_odd"));
?>
I currently loop through the array and collect values into another array.
foreach($percentage_array[$scenario_first] as $type => $value) {
$first = substr($type,0,$first_letters_count);
if(strlen($type)==$sc_type) {
if($first==$scenario) {
$percentages[] = $value;
$scenario_array[$type] = $value;
}
}
}
Instead of looping through the array, i want to get all keys that begin with x e.g. xaa, xab, xac
So instead i do $percentage_array[$scenario_first][beginning_with_x]
How do i do this?
EDIT: This is even easier:
$filtered_array = array_filter($array, function($key){
return $key{0} == 'x';
}, ARRAY_FILTER_USE_KEY);
Giving:
array(3) {
["xa"]=>
int(1)
["xb"]=>
int(2)
["xd"]=>
int(4)
}
https://3v4l.org/Zri7n
Original answer:
Not quite sure if I understand the example code, but if you want to remove all key/value pairs in an array based on whether it begins with a letter, you can:
$array = [
'xa' => 1,
'xb' => 2,
'yc' => 3,
'xd' => 4,
];
$filtered_keys = array_filter(array_keys($array), function($k){
return !($k{0} == 'x');
});
foreach ($filtered_keys as $v) {
unset($array[$v]);
}
https://3v4l.org/6810T
Didn't try to understand your question fully, but maybe this is what you are looking for, give it a try & do modification according to your need
$percentage_array = array(
'xaa' => 1,
'xab' => 1,
'xac' => 1,
'non' => 1,
'sox' => 1);
$pattern = "/^x(.*)/";
$filtered_array = preg_filter($pattern, "$0", array_keys( $percentage_array ));
echo "<pre>";
print_r($filtered_array);
Below is the output
Array
(
[0] => xaa
[1] => xab
[2] => xac
)
$cuisines = RestaurantProfile::select('cuisines')->get();
$cuisines_array = array();
foreach ($cuisines as $cuisine) {
$string = implode(",",json_decode($cuisine, true));
$array = explode(",", $string);
foreach ($array as $single) {
if (!in_array($single, $cuisines_array)) {
$cuisines_array[] = $single;
}
}
}
dd($cuisines_array);
I want $cuisines_array to have something like
array:33 [▼
0 => "Afghani"
1 => "Mughlai"
2 => "Chinese"
3 => "Indian"
4 => "continental"
5 => "south indian"
6 => "mughlai"
But I am getting as in the screenshot: output screenshot
My Cuisines attribute in table is database table.
Any leads?
You can use array_slice() :
...
foreach (array_slice($array, 0, 6) as $single) {
...
array_slice()
returns the sequence of elements from the array array as specified by
the offset and length parameters
I have the below code in a for..loop is there a way I can add values to the beginning of the array?
$data = array();
$initial = strtotime('11:00:00');
for (; $initial < strtotime("23:00:59"); $initial = strtotime("+15 minutes", $initial)) {
if ($initial > strtotime("+45 minutes", time())) {
$row['value'] = date('Hi', $initial);
$row['label'] = date('H:i', $initial);
$data['data'][] = $row;
}
}
I want to add the below values to the top of the array. I have tried using array_unshift but I don't think it supports key-value pairs.
if(!isBetween('22:00', '09:59', date('H:i'))) {
$row['value'] = "asap";
$row['label'] = "ASAP";
}
My array output
{
"data": [
{
"value": "1145",
"label": "11:45"
}
]
}
I want to get this
{
"data": [
{
"value": "asap",
"label": "ASAP"
},{
"value": "1145",
"label": "11:45"
},
]
}
Un-shift should work if you pass the arguments correctly:
array_unshift($data["data"], $prepend);
Alternatively, you could use array_merge, like this:
$data["data"] = array_merge(array($prepend), $data["data"]);
With the following example data:
$data = [
"data" => [
[
"value" => "1145",
"label" => "11:45"
]
]
];
$prepend = [
"value" => "asap",
"label" => "ASAP"
];
$data["data"] = array_merge(array($prepend), $data["data"]);
print_r($data);
You would get this output (with both solutions):
Array (
[data] => Array (
[0] => Array (
[value] => asap
[label] => ASAP
)
[1] => Array (
[value] => 1145
[label] => 11:45
)
)
)
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:
function array_unshift_assoc(&$arr, $key, $val) {
$arr = array_reverse($arr, true);
$arr[$key] = $val;
return array_reverse($arr, true);
}
Source: http://php.net/manual/en/function.array-unshift.php
I have a array like this:
Array
(
[0] => Chat Show
[1] => Non-fiction
[2] => Inspirational
)
And i am trying to get this format:
"genres": [
{
"name": "Chat Show"
},
{
"name": "Non-fiction"
},
{
"name": "Inspirational"
}
]
but i get something like this:
genres": [
"Chat Show",
"Non-fiction",
"Inspirational"
]
This is what i am doing:
while($row = mysqli_fetch_array($Data))
{
$Genres = explode('/', filter_var(rtrim($row['genres'], '/'), FILTER_SANITIZE_URL));
}
and then this is part of a bigger array
"genres" => $Genres
print_r(
json_encode(["genres" => array_map(
function($v) { return ['name' => $v]; },
$Genres)]));
result
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]}
For example, here is your array in PHP
$var = array(
"Chat Show",
"Non-fiction" ,
"Inspirational"
);
Without a key "name". You should create a new array and push each element as an array to your new array.
$result = array();
foreach($var as $name)
{
$arr = array("name"=>$name);
array_push($result, $arr);
}
after that, encode your $result by using json_encode
$json = json_encode($result,true);
echo $json;
Here is my output by echo $json.
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
Try this:
$Genres=array("Chat Show","Non-fiction","Non-fiction");
$new["genres"]=array();
foreach($Genres as $key => $name){
$new["genres"][$key] = ['name' => $name];
}
echo json_encode($new);
Output
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Non-fiction"}]}
The json string you posted here is not a valid json OR is part of json.
So, you might already have genres in your javascript, and want to get the remaining thing, which is
[
{ "name": "Chat Show" },
{ "name": "Non-fiction" },
{ "name": "Inspirational" }
]
Your current PHP $Genres looks like this because you are exploding the string
$Genres = [ 'Chat Show', 'Non-fiction', 'Inspirational' ];
Apply this to change values of your current $Genres
array_walk($Genres, function(&$v){ $v = ['name'=>$v]; });
Use it in your javascript like,
"genres": <?php json_encode($Genres)?>
Try this:
$genres_new['name']=$Genres;
echo json_encode($genres_new);
Your problem is, that you have simple array of strings, but you want an associative multilevel array. This is an relative simple operation. First lets illustrate the problem with some code:
// That is what you have, an :
$Genres = [
"Chat Show",
"Non-fiction",
"Inspirational",
];
// or the same for php > 5.4:
$Genres = array(
"Chat Show",
"Non-fiction",
"Inspirational",
);
This will produce the following json string (echo json_encode($Genres);):
["Chat Show","Non-fiction","Inspirational"]
But if you want such an output:
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
You have to convert the strings into an array. You can do that with that (or a similar loop):
foreach($Genres as $key => $name){
$Genres[$key] = ['name' => $name];
}
After that your array look like this:
Array (
0 =>
array (
'name' => 'Chat Show',
),
1 =>
array (
'name' => 'Non-fiction',
),
2 =>
array (
'name' => 'Inspirational',
),
)
Putting things together you will get something like that:
<?php
// Do whatever is necessary to build your Genres array ...
$Genres = [
"Chat Show",
"Non-fiction",
"Inspirational",
];
// Convert the array into an array of arrays
foreach($Genres as $key => $name){
$Genres[$key] = ['name' => $name];
}
echo json_encode($Genres);
/**
Now you will get this output:
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
*/
// After that you can add it to the bigger array:
$biggerArray = [];
$biggerArray['genres'] = $Genres;
echo json_encode($biggerArray);
/**
Output:
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]}
*/