Access JSON Array Data Within Object With PHP - php

stdClass Object (
[id] => 8586332
[email] => hello#myemail.com
[optInType] => Unknown
[emailType] => Html
[dataFields] => Array
(
[0] => stdClass Object ( [key] => FIRSTNAME [value] => Bill )
[1] => stdClass Object ( [key] => FULLNAME [value] => Bill Jones )
[2] => stdClass Object ( [key] => GENDER [value] => )
[3] => stdClass Object ( [key] => LASTNAME [value] => Jones )
[4] => stdClass Object ( [key] => LASTSUBSCRIBED [value] => 2019-12-20T21:13:20.359947Z )
[5] => stdClass Object ( [key] => POSTCODE [value] => )
[6] => stdClass Object ( [key] => THIS_KEY [value] => This Value )
)
[status] => Subscribed )
I have this JSON object and array in PHP that I have decoded.
I am trying to access 'This Value' but I am stuck.
I also need to find a way to do it where I don't know if it will always be number 6.
I have made these attempts:
$object->{"dataFields[1]"};
and
$object['dataFields'][6]['THIS_KEY'];
I can access the email like this:
echo $objec[1]->email;

You will need to search through the subarray for the qualifying object using the key property's value.
There will be functional techniques to do this, but I'll show a simple loop and break technique.
Code: (Demo)
$object = (object) [
'id'=> 8586332,
'email' => 'hello#myemail.com',
'optInType' => 'Unknown',
'emailType' => 'Html',
'dataFields' => [
(object)['key' => 'FIRSTNAME', 'value' => 'Bill'],
(object)['key' => 'FULLNAME', 'value' => 'Tom Jones'],
(object)['key' => 'GENDER', 'value' => ''],
(object)['key' => 'LASTNAME', 'value' => 'Jones'],
(object)['key' => 'LASTSUBSCRIBED', 'value' => '2019-12-20T21:13:20.359947Z'],
(object)['key' => 'POSTCODE', 'value' => ''],
(object)['key' => 'THIS_KEY', 'value' => 'This Value'],
],
'status' => 'Subscribed'
];
foreach ($object->dataFields as $dataRow) {
if ($dataRow->key === 'THIS_KEY') {
echo $dataRow->value;
break;
}
}
Output:
This Value
A functional search can look like this: (Demo)
$index = array_search('THIS_KEY', array_column($object->dataFields, 'key'));
if ($index !== false) {
echo $object->dataFields[$index]->value; // same output as above
}
If you want simpler access to multiple values in the subarray, then assign temporary keys: (Demo)
$assocDataFields = array_column($object->dataFields, null, 'key');
echo $assocDataFields['THIS_KEY']->value;
echo "\n";
echo $assocDataFields['FULLNAME']->value;
Output:
This Value
Tom Jones

Related

Convert multi-dimensional array to flat array php

I have a problem in converting multi-dimensional array to flat array
I have an input array like this:
Array
(
[0] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionCombine
[aggregator] => all
[conditions] => Array
(
[0] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => category_ids
)
)
)
[1] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => category_ids
)
[2] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => attribute_set_id
)
)
and I want the output is an array like this, the child array will be flattened as parent array level and it will be recognized by the index:
Array
(
[1--1] => Array
(
[type] => Magento\CatalogRule\Model\Rule\Condition\Combine
[aggregator] => all
)
[1--1--1] => Array
(
[type] => Magento\CatalogRule\Model\Rule\Condition\Product
[attribute] => category_ids
)
[1--2] => Array
(
[type] => Magento\CatalogRule\Model\Rule\Condition\Product
[attribute] => category_ids
)
[1--3] => Array
(
[type] => Magento\CatalogRule\Model\Rule\Condition\Product
[attribute] => attribute_set_id
)
)
the input array may contain many child layers and the output array must be index in that format.
I'm stucking to write this logic into code. Thank you!
You can use a recursive function like this:
function flatten($array, $parent_key = '1') {
$flattened_array = [];
foreach ($array as $key => $item) {
$tmp = $item;
unset($tmp['conditions']);
$child_key = $parent_key . '--' . strval($key + 1);
$flattened_array[$child_key] = $tmp;
if (isset($item['conditions'])) {
$flattened_array = array_merge($flattened_array, flatten($item['conditions'], $child_key));
}
}
return $flattened_array;
}
$input = [
0 => [
'type' => 'MagentoCatalogRuleModelRuleConditionCombine',
'aggregator' => 'all',
'conditions' => [
0 => [
'type' => 'MagentoCatalogRuleModelRuleConditionProduct',
'attribute' => 'category_ids'
]
]
],
1 => [
'type' => 'MagentoCatalogRuleModelRuleConditionProduct',
'attribute' => 'category_ids'
],
2 => [
'type' => 'MagentoCatalogRuleModelRuleConditionProduct',
'attribute' => 'attribute_set_id'
]
];
print_r(flatten($input));
Output:
Array
(
[1--1] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionCombine
[aggregator] => all
)
[1--1--1] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => category_ids
)
[1--2] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => category_ids
)
[1--3] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => attribute_set_id
)
)

Filter elements from multidimensional array that contain specific string

I have the following array
Array
(
[0] => Array
(
[text] => Array
(
[content] => I
[beginOffset] => 0
)
[partOfSpeech] => Array
(
[tag] => PRON
[aspect] => ASPECT_UNKNOWN
[case] => NOMINATIVE
[form] => FORM_UNKNOWN
[gender] => GENDER_UNKNOWN
[mood] => MOOD_UNKNOWN
[number] => SINGULAR
[person] => FIRST
[proper] => PROPER_UNKNOWN
[reciprocity] => RECIPROCITY_UNKNOWN
[tense] => TENSE_UNKNOWN
[voice] => VOICE_UNKNOWN
)
[dependencyEdge] => Array
(
[headTokenIndex] => 1
[label] => NSUBJ
)
[lemma] => I
)
...
I want to remove all elements that contain the string "_UNKNOWN" as they are not necessairy
how would I go about that?
Assuming all your 'UNKNOWN' are going to be in 'partOfSpeech', you can use this simple code to remove all the elements containing the string '_UNKNOWN':
$array = ['text' => ['content' => 'I', 'beginOffset' => 0], 'partOfSpeech' => ['tag' => 'PRON', 'aspect' => 'ASPECT_UNKNOWN', 'form' => 'FORM_UNKNOWN']]; // Example array
$array['partOfSpeech'] = array_filter($array['partOfSpeech'],
function($item) {
return strpos($item, '_UNKNOWN') === false;
});
print_r($array);
Output:
Array ( [text] => Array ( [content] => I [beginOffset] => 0 ) [partOfSpeech] => Array ( [tag] => PRON ) )

make nested array on the basis of specific array value in php

Array
(
[0] => Array
(
[user_id] => 40718
[name] => abc1
)
[1] => Array
(
[user_id] => 40718
[name] => abc2
)
[2] => Array
(
[user_id] => 40719
[name] => abc3
)
)
my array is like having user_id as you can see above i want to convert it into nested array on the basis of specific value from array as user_id like mention below
Array
(
[40718] => Array
(
[0]=>array(
[name] => abc1
)
[1]=>array(
[name] => abc2
)
)
[40719] => Array
(
[0] => (
[name] => abc3
)
)
)
Though I haven't tested it, check if it can help you to get your result :
<?php
$arrTest = [
[
'user_id' => 40718,
'name' => 'abc1'
],
[
'user_id' => 40718,
'name' => 'abc2'
],
[
'user_id' => 40719,
'name' => 'abc3'
]
];
$resultArr = [];
foreach ($arrTest as $val) {
$resultArr[$val['user_id']][]['name'] = $val['name'];
}
echo '<pre>'; print_r($resultArr); exit;
?>

merge two array with the same key and value

I have arrays of $array_one:
print_r($array_one);
Array
(
[0] => stdClass Object
(
[myid] => 653509
[date] => 2015-03-15 00:07:03
)
[1] => stdClass Object
(
[myid] => 653511
[date] => Never
)
[2] => stdClass Object
(
[myid] => 653530
[date] => 2015-03-15 02:06:26
)
And then the arrays of $array_two;
print_r($array_two);
Array
(
[0] => stdClass Object
(
[myid] => 653530
[pin] => 12fdg34345
)
[1] => stdClass Object
(
[myid] => 653509
[pin] => 1we2534dgf5
)
[2] => stdClass Object
(
[myid] => 653511
[pin] => 12wer3u45
)
and then I want to merge it based on the keys with the same value, in which the expected result would be:
Array
(
[0] => stdClass Object
(
[myid] => 653530
[pin] => 12fdg34345
[date] => 2015-03-15 02:06:26
)
[1] => stdClass Object
(
[myid] => 653509
[pin] => 1we2534dgf5
[date] => 2015-03-15 00:07:03
)
[2] => stdClass Object
(
[myid] => 653511
[pin] => 12wer3u45
[date] => Never
)
from the result above, the array key of date from the first_array is push to
the second_array based on the similar value of the key of my_id.
Is there a way to do this?
Please help and many thanks for the help.
Cheers!
As per my comment, this solution depends on the structure changing very slightly, to be arrays of associative arrays, not arrays of objects. As you said the data is coming from (a) database(s), if you're using something like PDO, this should just mean a small change to set the correct fetch mode.
The result can be achieved by combining the php built-in functions array_column and array_replace_recursive. If you want the resulting array to still be 0-indexed, we can use array_values too.
$array_one = [
[
'myid' => 653509,
'date' => '2015-03-15 00:07:03'
],
[
'myid' => 653511,
'date' => 'Never'
],
[
'myid' => 653530,
'date' => '2015-03-15 02:06:26'
]
];
$array_two = [
[
'myid' => 653530,
'pin' => '12fdg34345'
],
[
'myid' => 653509,
'pin' => '1we2534dgf5'
],
[
'myid' => 653511,
'pin' => '12wer3u45'
]
];
$merged = array_replace_recursive(
array_column($array_one, null, 'myid'),
array_column($array_two, null, 'myid')
);
<?php
$temp_arr_one = array();
foreach($array_one as $key1=>$val1){
$temp_arr_one[$val1['myid']] = $val1->date;
}
$final_arr = array();
foreach($array_two as $key2=>$val2){
$final_arr[$key2]['myid'] = $val2->myid;
$final_arr[$key2]['pin'] = $val2->pin;
$final_arr[$key2]['date'] = $temp_arr_one[$val2->myid];
}
print_r($final_arr);
?>

Remove only associative array with all values empty

Is it possible to remove only the associative array who have all values empty?
Data source:
Array
(
[0] => Array
(
[name] => foo
[phone] => 012345
[email] =>
)
[1] => Array
(
[name] => bar
[phone] =>
[email] => yahoo.com
)
[2] => Array
(
[name] =>
[phone] =>
[email] =>
)
)
Desired output:
Array
(
[0] => Array
(
[name] => foo
[phone] => 012345
[email] =>
)
[1] => Array
(
[name] => bar
[phone] =>
[email] => yahoo.com
)
)
I tried this, but unfortunately I will delete all empty values ​​of arrays
$_arr = array_filter(array_map('array_filter', $_arr));
Array
(
[0] => Array
(
[name] => foo
[phone] => 012345
)
[1] => Array
(
[name] => bar
[email] => yahoo.com
)
)
How could I do it? Thank You
Maybe a slicker way, but:
$array = array_filter($array, function($a) { return array_filter($a); });
Since array_filter is using a true or false return to filter; the array_filter in the function is returning either an empty array evaluated as false, or a non-empty array evaluated as true, and the main array_filter is filtering based upon that.
<?php
$collection = array(
"0" => array
(
'name' => "foo",
'phone' => "012345",
'email' => ''
),
"1" => array
(
'name' => "bar",
'phone' => '',
'email' => "yahoo.com",
),
"2" => array
(
'name' => '',
'phone' => '',
'email' => ''
)
);
foreach($collection as $key=> $entry){
if(count(array_filter($entry)) == 0){
unset($collection[$key]);
}
}
print_r($collection);

Categories