How can in php get the value name out of this object and out of this array of objects? And how can check is object or array object and then get value name?
"director": {
"#type": "Person",
"url": "/name/nm0001104/",
"name": "Frank Darabont"}
"director": [
{
"#type": "Person",
"url": "/name/nm5156926/",
"name": "Devon Downs"
},
{
"#type": "Person",
"url": "/name/nm2632302/",
"name": "Kenny Gage"
}],
$json = '{
"director": [
{
"#type": "Person",
"url": "/name/nm5156926/",
"name": "Devon Downs"
},
{
"#type": "Person",
"url": "/name/nm2632302/",
"name": "Kenny Gage"
}
]
}';
$names = [];
$data = json_decode($json, true);
if (true === isset($data['name'])) {
$name[] = $data['name'];
return $names;
}
foreach ($data as $director) {
foreach($director as $itme){
if (true === isset($itme['name'])) {
$names[] = $itme['name'];
}
}
}
return $names;
Output :
Array
(
[0] => Devon Downs
[1] => Kenny Gage
)
use json_decode.
$names = [];
$data = json_decode($json, true);
if (true === isset($data['name'])) {
$name[] = $data['name'];
return $names;
}
foreach ($data as $director) {
if (true === isset($director['name'])) {
$names[] = $director['name'];
}
}
return $names;
Related
I wrote some PHP code to line up the children of an array. I wrote a recursive function.
Everything is listed correctly one below the other, but some arrays do not have the "Name" key.
Does anyone have any idea how I can get it to show everyone's "Name" key?
My PHP Code:
$json = '[
{
"name": "A",
"children": [
{
"name": "B",
"children": [
{
"name": "C"
},
{
"name": "D",
"children": [
{
"name": "E"
},
{
"name": "F"
}
]
}
]
},
{
"name": "G"
}
]
},
{
"name": "H"
}
]';
header('Content-Type: application/json; charset=utf-8');
$json = json_decode($json, true);
function array_flatten($array, $prefix = '') {
$return = array();
foreach ($array as $key => $value) {
if (is_array($value) && array_key_exists("children", $value)){
$return = array_merge($return, array_flatten($value, $key));
}else if (is_array($value) && count($value) > 1){
foreach ($value as $keyA => $valueA) {
if (is_array($valueA) && array_key_exists("children", $valueA)){
$return = array_merge($return, array_flatten($valueA, $keyA));
}else{
$return[] = $valueA;
}
}
} else {
$return[] = $value;
}
}
return $return;
}
echo json_encode(array_flatten($json));
Current Result:
["A","B",{"name":"C"},"D",{"name":"E"},{"name":"F"},{"name":"G"},{"name":"H"}]
What I want:
[{"name":"A"},{"name":"B"},{"name":"C"},{"name":"D"},{"name":"E"},{"name":"F"},{"name":"G"},{"name":"H"}]
Here is a working code :
<?php
$json = '[
{
"name": "A",
"children": [
{
"name": "B",
"children": [
{
"name": "C"
},
{
"name": "D",
"children": [
{
"name": "E"
},
{
"name": "F"
}
]
}
]
},
{
"name": "G"
}
]
},
{
"name": "H"
}
]';
$json = json_decode($json, true);
function getArrayValuesRecursively(array $array){
$values = [];
foreach ($array as $value) {
if (is_array($value)) {
$values = array_merge(
$values,
getArrayValuesRecursively($value)
);
} else {
$values[] = ['name' => $value];
}
}
return $values;
}
echo json_encode(getArrayValuesRecursively($json));
Demo : https://3v4l.org/01Fla
Function getArrayValuesRecursively(array $array) is from Get all values from multidimensional array
here's my take on it:
$json = json_decode($json, true);
$names = get_names_of_people($json);
print(json_encode($names));
function get_names_of_people(array $people): array
{
$names = [];
foreach ($people as $person) {
foreach ($person as $key => $value) {
switch ($key) {
case 'name':
$names[] = [
'name' => $value,
];
break;
case 'children':
$names = array_merge($names, get_names_of_people($value));
}
}
}
return $names;
}
$array = json_decode($json, true);
$result = [];
array_walk_recursive($array, function ($value, $key) use(&$result) {
$result[][$key] = $value;
});
Here is my JSON
[
{
"TIMESTAMP": "2021-06-09 13:13:26",
"COL1": "10",
"COL2": "20",
"COL3": "30"
},
{
"TIMESTAMP": "2021-06-22 13:13:26",
"COL1": "20",
"COL2": "30",
"COL3": "40"
},
{
"TIMESTAMP": "2021-06-21 13:13:26",
"COL1": "1",
"COL2": "2",
"COL3": "3"
},
{
"TIMESTAMP": "2021-06-20 13:13:26",
"COL1": "40",
"COL2": "50",
"COL3": "60"
}
]
I need to refactor the json According to the Column name like (EXPECTED OUTPUT)
[
{
"TITLE":"COL1"
"DATA":[10,20,1,40]
},
{
"TITLE":"COL2"
"DATA":[20,30,2,50]
},
{
"TITLE":"COL3"
"DATA":[30,40,3,60]
},
]
I was tried but it not working
$data = json_decode($result, true);
$refactored = array_map(function($item) {
return (object)[
'TIMESTAMP' => $item['TIMESTAMP'],
'DATA' => [ $item['COL1'], $item['COL2'], $item['COL3'] ]
];
}, $data);
dump($refactored);
Someone help me out with this. The column may be 3 or more and it must be dynamic. Thanks in advance.
You can transform your JSON like this:
$data = json_decode($result, true);
$refactored = array_reduce($json, function($carry, $item) {
foreach($item as $key => $value) {
if (str_starts_with($key, 'COL')) {
$index = substr($key, 3, 1) - 1;
if (!isset($carry[$index])) {
$carry[$index] = [
'Title' => $key
];
}
$carry[$index]['Data'][] = $value;
}
}
return $carry;
}, []);
dump($refactored);
I am always a fan of using the value you want to group your data by as a temporary array key, that makes things easier, and can simply be reset by using array_values afterwards.
$input = json_decode('…', true);
$output = [];
foreach($input as $item) {
foreach($item as $key => $value) {
if($key != 'TIMESTAMP') {
$output[$key]['TITLE'] = $key;
$output[$key]['DATA'][] = (int)$value;
}
}
}
$output = array_values($output);
echo json_encode($output);
All you have to do is re-encode the processed data:
json_encode($refactored) will give you the output that you want.
P.S. you don't have to cast to an object. It works as array as well.
I have PHP array defined like this:
{
"data": [
{
"content": "Build your communication",
"property": null,
"name": "description"
},
{
"content": "simplify it",
"property": "og:title",
"name": null
},
{
"content": "unleash the effectiveness",
"property": "og:description",
"name": null
},
{
"content": "https:\/\/uploads-ssl.webflow.com\/\/%%20SETTINGS.png",
"property": "og:image",
"name": null
}
}
How can I search trough property keys and return just array groups where property field with values og: as a part of the string is defined.
$crawler = new Crawler(file_get_contents($url));
$items = $crawler->filter('meta');
$metaData = [];
foreach ($items as $item) {
$itemCrawler = new Crawler($item);
$content = $itemCrawler->eq(0)->attr('content');
$property = $itemCrawler->eq(0)->attr('property');
$name = $itemCrawler->eq(0)->attr('name');
$metaData = [
'content' => $content,
'property' => $property,
'name' => $name,
];
}
return $metaData;;
Tried with :
if(substr( $data['property'], 0, 3 ) === 'og:') {}
Returns just first one.
Can someone help?
This should work for you. $ret will hold all objects where the property "property" contains "og:".
$items = json_decode('{
"data": [
{
"content": "Build your communication",
"property": null,
"name": "description"
},
{
"content": "simplify it",
"property": "og:title",
"name": null
},
{
"content": "unleash the effectiveness",
"property": "og:description",
"name": null
},
{
"content": "https:\/\/uploads-ssl.webflow.com\/\/%%20SETTINGS.png",
"property": "og:image",
"name": null
}
]}');
$ret = array_filter($items->data, function($item) {
return strstr($item->property, "og:");
});
$data = [];
foreach ($items["data"] as $item) {
$content = item['content'];
$property = item['property'];
$name = item['name'];
$temp= [
'content' => $content,
'property' => $property,
'name' => $name,
];
array_push($data,$temp);
}
You have a "data" keyword before the array. Try this
For 2 days, I'm trying to extract informations from a multidimensional array and I think I'm stuck after trying a lot of things
Here is my json
{
"profile": [
{
"id": "123456",
"hostId": null,
"description": [
{
"id": "name",
"value": "foo"
},
{
"id": "name2",
"value": "foo2"
},
{
"id": "bio",
"value": "heyyyy"
},
{
"id": "location",
"value": "somewhere"
}
],
"ishere": true
}
]
}
I want to manipulate it to have this
{
"id": "123456",
"host": null,
"name": "foo",
"name2": "foo2",
"bio": "heyyyy",
"location": "somewhere",
"ishere": true
}
with this (after a json_decode)
foreach ($array->profileUsers[0]->settings as $item) {
$out2[$item->id] = $item->value;
}
I only have
{
"name": "foo",
"name2": "foo2",
"bio": "heyyyy",
"location": "somewhere"
}
Thank you
This should do the trick:
$obj = json_decode($your_json);
$obj = $obj->profile[0];
foreach($obj->description as $d)
$obj->{$d->id} = $d->value;
unset($obj->description);
$data = json_decode($your_json, true);
$new_array = [];
foreach($data['profile'] as $key=>$item) {
if(is_array($item)) {
$new_array[$item['id']] = $item['value'];
}
else {
$new_array[$key] = $item;
}
}
Hardcoded this, hope it will help.
I need a help. I'm looking for a solution for this problem!
I have a file which contains the following pattern:
Brazil|SaoPaulo|Diadema|RuadaFe Brazil|SaoPaulo|Diadema|RuadoLimoeiro
Brazil|SaoPaulo|SaoCaetano|RuadasLaranjeiras
Brazil|Parana|Curitiba|ComendadorAraujo
USA|NewJersey|JerseyCity|WhashingtonBoulervard
USA|NewJersey|JerseyCity|RiverCourt
Which should bring after some array key implementation, something like this (after apply json_encode call on php):
{
"name": "Brazil",
"children": [
{
"name": "SaoPaulo",
"children": [
{
"name": "Diadema",
"children": [
{"name": "RuadaFe"},
{"name": "RuadoLimoeiro"}
]
},
{
"name": "SaoCaetano",
"children": [
{"name": "RuadasLaranjeiras"}
]
},
]
"name": "Parana",
"children": [
{
"name": "Curitiba",
"children": [
{"name": "ComendadorAraujo"}
]
}
]
},
"name":"USA",
"children":[
{
"name": "NewJersey",
"children": [
{
"name": "JerseyCity",
"children": [
{"name": "WhashingonBoulevard"},
{"name": "RiverCourt"}
]
}
]
}
]
}
]
And keep going and going (and even more deeper too).
Please, help me team... thanks in advance.
Here what I get until now:
Array
(
[Brazil] => Array
(
[SaoPaulo] => Array
(
[Diadema] => Array
(
[RuadoLimoeiro] =>
)
[SaoCaetano] => Array
(
[RuadasLaranjeiras] =>
)
)
[Parana] => Array
(
[Curitiba] => Array
(
[ComendadorAraujo] =>
)
)
)
[USA] => Array
(
[NewJersey] => Array
(
[JerseyCity] => Array
(
[WhashingtonBoulervard] =>
[RiverCourt] =>
)
)
)
)
And here is the json encoded:
{
"Brazil":{
"SaoPaulo":
{"Diadema":
{"RuadoLimoeiro":null},
"SaoCaetano":{"RuadasLaranjeiras":null}
},
"Parana":
{"Curitiba":
{"ComendadorAraujo":null}
}
},
"USA":{
"NewJersey":{
"JerseyCity":{
"WhashingtonBoulervard":null,
"RiverCourt":null}
}
}
}
As you can see, the "names" and "child" is missing because is not an array key structure, also something is wrong, because I'm missing some values on SaoPaulo.
Here is the function:
foreach($strings as $string) {
$parts = array_filter(explode('|', $string));
$ref = &$result;
foreach($parts as $p) {
// echo $p;
if(!isset($ref[$p])) {
$ref[$p] = array();
// $ref[$p] = array("name"=>$p);
}
$ref = &$ref[$p];
}
$ref = null;
}
-------------------------------- AFTER SOME ANSWERS --------------------------
{
"name": "Brazil(country)",
"children": [
{
"name": "SaoPaulo(state)", // only one state
"children": [
{
"name": "Diadema(city)", // only one city
"children": [
{"name": "RuadaFe(street)"}, // two streets under the same city...
{"name": "RuadoLimoeiro(street)"}
]
},
{
"name": "SaoCaetano(city)",
"children": [
{"name": "RuadasLaranjeiras(street)"}
]
},
]
"name": "Parana(state)",
"children": [
{
"name": "Curitiba(city)",
"children": [
{"name": "ComendadorAraujo(street)"}
]
}
]
},...
I put on parentesis the structure (country, state, city, street) just to clarify what i want.
Got it?
It is not outright trivial, but what I did is actually the same as you (the same way as in your edited question), but I also keep track of those arrays to rename the keys. And that's what I do afterwards then:
$separator = [' ', '|'];
$buffer = file_get_contents($file);
$entries = explode($separator[0], $buffer);
$result = [];
$named[] = &$result;
########
foreach ($entries as $entry) {
$each = explode($separator[1], $entry);
$pointer = & $result;
while ($current = array_shift($each)) {
if (!isset($pointer[$current])) {
unset($children);
$children = [];
$named[] = &$children;
########
$pointer[$current] = ['name' => $current, 'children' => &$children];
}
$pointer = & $pointer[$current]['children'];
}
}
foreach($named as $offset => $namedArray) {
$keys = array_keys($namedArray);
foreach($keys as $key) {
$named[$offset][] = &$namedArray[$key];
unset($named[$offset][$key]);
}
}
print_r($result);
See it in action.
You probably might want to modify this by checking in the later foreach if children are empty (leaf-nodes) and then removing the children entry as well.
Here the modified foreach at the end and json output:
foreach($named as $offset => $namedArray) {
$keys = array_keys($namedArray);
foreach($keys as $key) {
if (!$namedArray[$key]['children']) {
unset($namedArray[$key]['children']);
}
$named[$offset][] = &$namedArray[$key];
unset($named[$offset][$key]);
}
}
echo json_encode($result, JSON_PRETTY_PRINT);
Output:
[
{
"name": "Brazil",
"children": [
{
"name": "SaoPaulo",
"children": [
{
"name": "Diadema",
"children": [
{
"name": "RuadaFe"
},
{
"name": "RuadoLimoeiro"
}
]
},
{
"name": "SaoCaetano",
"children": [
{
"name": "RuadasLaranjeiras"
}
]
}
]
},
{
"name": "Parana",
"children": [
{
"name": "Curitiba",
"children": [
{
"name": "ComendadorAraujo"
}
]
}
]
}
]
},
{
"name": "USA",
"children": [
{
"name": "NewJersey",
"children": [
{
"name": "JerseyCity",
"children": [
{
"name": "WhashingtonBoulervard"
},
{
"name": "RiverCourt"
}
]
}
]
}
]
}
]
The full code-example at a glance:
<?php
/**
* PHP - Nested array keys based on string lines
* #link http://stackoverflow.com/a/16305236/2261774
*/
$file = 'data://text/plain;base64,' . base64_encode('Brazil|SaoPaulo|Diadema|RuadaFe Brazil|SaoPaulo|Diadema|RuadoLimoeiro Brazil|SaoPaulo|SaoCaetano|RuadasLaranjeiras Brazil|Parana|Curitiba|ComendadorAraujo USA|NewJersey|JerseyCity|WhashingtonBoulervard USA|NewJersey|JerseyCity|RiverCourt');
$separator = [' ', '|'];
$buffer = file_get_contents($file);
$entries = explode($separator[0], $buffer);
$result = [];
$named[] = &$result;
foreach ($entries as $entry) {
$each = explode($separator[1], $entry);
$pointer = & $result;
while ($current = array_shift($each)) {
if (!isset($pointer[$current])) {
unset($children);
$children = [];
$named[] = &$children;
$pointer[$current] = ['name' => $current, 'children' => &$children];
}
$pointer = & $pointer[$current]['children'];
}
}
unset($pointer);
foreach($named as $offset => $namedArray) {
$keys = array_keys($namedArray);
foreach($keys as $key) {
if (!$namedArray[$key]['children']) {
unset($namedArray[$key]['children']);
}
$named[$offset][] = &$namedArray[$key];
unset($named[$offset][$key]);
}
}
unset($named);
echo json_encode($result, JSON_PRETTY_PRINT);
your question JSON:
{
"name": "Brazil",
"children": [
{
"name": "SaoPaulo",
"children": [
{
"name": "Diadema",
"children": [
{"name": "RuadaFe"},
{"name": "RuadoLimoeiro"}
]
},
My Answer JSON:
[
{
"name": "Brazil",
"children": [
{
"name": "SaoPaulo",
"children": [
{
"name": "Diadema",
"children": [
{
"name": "RuadaFe"
},
{
"name": "RuadoLimoeiro"
}
]
},
The only difference I can spot is that the root-nodes are wrapped inside an array in my answer, but it should be trivial to fetch them out there if that really is your issue ;)
Does it solves your problem? Use $inputString to put your real string.
<?php
// ------------------------------------------------------ your input goes here ------------------------------------------------------
$inputString = 'Brazil|SaoPaulo|Diadema|RuadaFe Brazil|SaoPaulo|Diadema|RuadoLimoeiro Brazil|SaoPaulo|SaoCaetano|RuadasLaranjeiras Brazil|Parana|Curitiba|ComendadorAraujo USA|NewJersey|JerseyCity|WhashingtonBoulervard USA|NewJersey|JerseyCity|RiverCourt';
class item {
public $name = null;
public function getChildrenByName($strName) {
$ret = null;
# this variable should be defined in interface, but i skipped it so it wont be printed in json when obj does not have childrens
if( !isset( $this->children ) ) {
$this->children = array( );
}
foreach ( $this->children as $child ) {
if( $child->name === $strName ) {
$ret = $child;
break;
}
}
if ( !$ret ) {
$this->children[] = self::spawnByName( $strName );
}
return $this->children[ count($this->children) - 1];
}
static public function spawnByName($strName) {
$ret = new item();
$ret->name = $strName;
return $ret;
}
}
class listManager {
protected $list = array();
public function getList() {
return $this->list;
}
public function addPath( $desiredPath ) {
# path needs to be as array
if ( is_string( $desiredPath ) ) {
$desiredPath = explode('|', $desiredPath);
}
# create root element if it does not already exists
if ( !isset( $this->list[$desiredPath[0]] ) ) {
$this->list[$desiredPath[0]] = item::spawnByName($desiredPath[0]);
}
$curElement = $this->list[$desiredPath[0]];
for( $i=1; $i<count($desiredPath); $i++ ) {
$curElement = $curElement->getChildrenByName( $desiredPath[$i] );
}
}
protected function spawnElement( $strName ) {
$ret = new item();
$ret->name = $strName;
return $ret;
}
}
$output = array();
$expl = explode(' ', $inputString);
$list = new listManager();
foreach ( $expl as $key => $path ) {
$list->addPath( $path );
}
$output = '';
foreach ( $list->getList() as $singleVariable ) {
$output .= json_encode($singleVariable, JSON_PRETTY_PRINT) . ",\n";
}
echo '<pre>'.$output.'</pre>';
?>
Above code produces following json out of your sample code:
{
"name": "Brazil",
"children": [{
"name": "SaoPaulo",
"children": [{
"name": "Diadema",
"children": [{
"name": "RuadaFe"
}
]
}
]
}, {
"name": "SaoPaulo",
"children": [{
"name": "Diadema",
"children": [{
"name": "RuadoLimoeiro"
}
]
}
]
}, {
"name": "SaoPaulo",
"children": [{
"name": "SaoCaetano",
"children": [{
"name": "RuadasLaranjeiras"
}
]
}
]
}, {
"name": "Parana",
"children": [{
"name": "Curitiba",
"children": [{
"name": "ComendadorAraujo"
}
]
}
]
}
]
} {
"name": "USA",
"children": [{
"name": "NewJersey",
"children": [{
"name": "JerseyCity",
"children": [{
"name": "WhashingtonBoulervard"
}
]
}
]
}, {
"name": "NewJersey",
"children": [{
"name": "JerseyCity",
"children": [{
"name": "RiverCourt"
}
]
}
]
}
]
}
edit: changed, does it fit now?