To print the value of array.under array - php

I have to print the all the value of the array written value.
[subscriber] => Array
(
[name] => Subscriber
[capabilities] => Array
(
[read] => 1
[level_0] => 1
)
[default] => Array
(
[deft] => Array (
[one] => 2
[two] => 3
)
[deft_one] => Array (
[one] => t
[two] => h
)
)
)
I have to print each value under the array. So i used a recursion function. But i cant the result. Please help me in recursion function.
Sorry, I am trying till now. Actually i have to print the wp-option table value. There are many serialise array. I want to print all the value individually. I mean when i used the code written bellow i got an array.
function option_value_change () {
global $wpdb;
$myrows = $wpdb->get_results( "SELECT *
FROM `wp_options`");
$temp_url = get_option('siteurl');
$site_url = get_site_url();
foreach ($myrows as $rows){
$option = get_option($rows->option_name);
//print_r($option);
get_option_value($option);
}
}
i can get the table. But in an array. Which array have arrays. So i used an function "get_option_value($option)". as written bellow
function get_option_value($option) {
if(!is_object($option) && !is_array($option)){
echo $option;
}
else{
foreach($option as $option_value){
if(!is_array($option_value)){
echo $option_value;
}
else {
get_option_value($option_value);
}
}
}
}
bUt i cant get all the value. its give an error as
Object of class stdClass could not be converted to string.
So how can i print all the values of the array.

You can use RecursiveArrayIterator example :
$data = array(
'subscriber' => array(
'name' => 'Subscriber',
'capabilities' => array(
'read' => 1,
'level_0' => 1,
),
'default' => array(
'deft' => array(
'one' => 2,
'two' => 3,
),
'deft_one' => array(
'one' => 't',
'two' => 'h',
),
),
),
);
echo "<pre>";
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
foreach($it as $var)
{
echo $var , PHP_EOL ;
}
Output
Subscriber
1
1
2
3
t
h

I didn't test it but you can get the idea;
function printArr($obj){
if(!is_array($obj)){
echo $obj;
return;
}
else if(is_array($obj)){
foreach ($obj as $key => $value) {
printArr($obj[$key]);
}
}
}

Related

Parse through unordered multidimensional array finding only strings

I have a multidimensional array of undefined depth.
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo",
"something" => 42,
"something2" => [1,2,3]
)
)
);
I need to parse through it, find all the values that are plane text and save them in another array keeping the pathway. So I expect the final array be like this:
$array = array(
"foo" => "bar",
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
At the moment I'm trying to use recurrent function
$this->printAll($array);
public function printAll($a)
{
if (!is_array($a)) {
echo $a, ' <br>'; // here we can check if it is string and add to the final array
return;
}
foreach($a as $i=>$v) {
$this->printAll($v);
echo $i;
}
}
Could someone help me to figure out how to keep indexes through iterations and put it in the final array.
<?php
function printAll($array, &$save)
{
foreach ($array as $key => $values)
{
if ( ! is_numeric($values))
{
if (is_array($values))
{
printAll($values, $save[$key]);
}
else
{
$save[$key] = $values;
}
}
}
if ( ! empty($save)) {
$save = array_filter($save);
}
}
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo",
"something" => 42,
"something2" => [1,2,3]
)
)
);
$save = array();
printAll($array, $save);
print_r($save);
Outputs: PHP
Array (
[foo] => bar
[multi] => Array (
[dimensional] => Array (
[array] => foo
)))

Compare element in array and loop through each php

I want to compare a value of data to a list of element which I had retrieved from php array(decoded json).
First,
This is the first array:
Array1
(
[0] => Array
(
[member_id] => 3
[member_card_num] => 2013011192330791
[member_barcode] => 2300067628912
)
[1] => Array
(
[member_id] => 4
[member_card_num] => 2328482492740000
[member_barcode] => 3545637000
)
[2] => Array
(
[member_id] => 2
[member_card_num] => 40001974318
[member_barcode] => 486126
)
[3] => Array
(
[member_id] => 1
[member_card_num] => 91001310000057698
[member_barcode] => 000057698
)
)
This is the second Array:
Array2
(
[0] => Array
(
[member_id] => 2
[member_card_num] => 40001974318
[member_barcode] => 486126
)
)
Second,
I had retrieved the (member_barcode) which I required.
Here is the code:
For Array1:
foreach ($decode1 as $d){
$merchant_barcode = $d ['member_barcode'];
echo $merchant_barcode;
}
For Array2:
foreach ($decode2 as $d2){
$user_barcode = $d2 ['member_barcode'];
echo $user_barcode;
}
Then,
I get this output():
For Array1(merchant_barcode):
2300067628912
3545637000
486126
000057698
For Array2(user_barcode):
486126
The question is, I would to check and compare whether the user_barcode in Array2(486126) is exist/match to one of the merchant_barcode in Array1.
This is my code,
but it only compare the user_barcode in Array2 to the last element(000057698) in Array1,
I want it to loop through each n check one by one. How can I do that?
public function actionCompareBarcode($user_barcode, $merchant_barcode){
if(($user_barcode) == ($merchant_barcode)){
echo "barcode exist. ";
}
else{
echo "barcode not exist";
}
}
In this case, the output I get is "barcode not exist", but it should be "barcode exist".
Anyone can help? Appreciate that. Im kinda new to php.
You could use a nested loop like:
foreach ($decode2 as $d2)
{
$user_barcode = $d2 ['member_barcode'];
foreach ($decode1 as $d)
{
$merchant_barcode = $d ['member_barcode'];
if ($merchant_barcode == $user_barcode)
{
echo "Match found!";
}
else
{
echo "No match found!";
}
}
}
<?
$a = array(
array(
'member_id' => 3,
'member_card_num' => '2013011192330791',
'member_barcode' => '2300067628912',
),
array(
'member_id' => 4,
'member_card_num' => '2328482492740000',
'member_barcode' => '3545637000',
),
array(
'member_id' => 2,
'member_card_num' => '40001974318',
'member_barcode' => '486126',
),
array(
'member_id' => 1,
'member_card_num' => '91001310000057698',
'member_barcode' => '000057698',
)
);
$b = array(
array(
'member_id' => 2,
'member_card_num' => '40001974318',
'member_barcode' => '486126',
)
);
array_walk($a, function($item) use($b) {
echo ($b['0']['member_barcode'] == $item['member_barcode'] ? "found" : NULL);
});
?>
I'd use array_uintersect() to calculate if those multidimensional arrays have a common element:
<?php
$a = array(
array(
'member_id' => '3',
'member_card_num' => '2013011192330791',
'member_barcode' => '2300067628912',
),
array(
'member_id' => '2',
'member_card_num' => '40001974318',
'member_barcode' => '486126',
)
);
$b = array(
array(
'member_id' => '2',
'member_card_num' => '40001974318',
'member_barcode' => '486126',
)
);
$match = array_uintersect($a, $b, function($valueA, $valueB) {
return strcasecmp($valueA['member_barcode'], $valueB['member_barcode']);
});
print_r($match);
Try calling that method as you are looping through Array1 and comparing the user_barcode to every value
You can compare two array this way too:
$per_arr = array();
$permissions = array()
foreach ($per_arr as $key => $perms) {
if(isset($permissions[$key]['name'])){
echo $per_arr[$key]['name']; //matched data
}else{
echo $per_arr[$key]['name']; //not matched data
}
}

How do I reform this array into a differently structured array

I have an array that looks like this:
[0] => Array
(
[name] => typeOfMusic
[value] => this_music_choice
)
[1] => Array
(
[name] => myMusicChoice
[value] => 9
)
[2] => Array
(
[name] => myMusicChoice
[value] => 8
)
I would like to reform this into something with roughly the following structure:
Array(
"typeOfMusic" => "this_music_choice",
"myMusicChoice" => array(9, 8)
)
I have written the following but it doesn't work:
foreach($originalArray as $key => $value) {
if( !empty($return[$value["name"]]) ){
$return[$value["name"]][] = $value["value"];
} else {
$return[$value["name"]] = $value["value"];
}
}
return $return;
I've tried lots of different combinations to try and get this working. My original array could contain several sets of keys that need converting to arrays (i.e. it's not always going to be just "myMusicChoice" that needs converting to an array) ?
I'm getting nowhere with this and would appreciate a little help. Many thanks.
You just need to loop over the data and create a new array with the name/value. If you see a repeat name, then change the value into an array.
Something like this:
$return = array();
foreach($originalArray as $data){
if(!isset($return[$data['name']])){
// This is the first time we've seen this name,
// it's not in $return, so let's add it
$return[$data['name']] = $data['value'];
}
elseif(!is_array($return[$data['name']])){
// We've seen this key before, but it's not already an array
// let's convert it to an array
$return[$data['name']] = array($return[$data['name']], $data['value']);
}
else{
// We've seen this key before, so let's just add to the array
$return[$data['name']][] = $data['value'];
}
}
DEMO: https://eval.in/173852
Here's a clean solution, which uses array_reduce
$a = [
[
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
],
[
'name' => 'myMusicChoice',
'value' => 9
],
[
'name' => 'myMusicChoice',
'value' => 8
]
];
$r = array_reduce($a, function(&$array, $item){
// Has this key been initialized yet?
if (empty($array[$item['name']])) {
$array[$item['name']] = [];
}
$array[$item['name']][] = $item['value'];
return $array;
}, []);
$arr = array(
0 => array(
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
),
1 => array(
'name' => 'myMusicChoice',
'value' => 9
),
2 => array(
'name' => 'myMusicChoice',
'value' => 8
)
);
$newArr = array();
$name = 'name';
$value = 'value';
$x = 0;
foreach($arr as $row) {
if ($x == 0) {
$newArr[$row[$$name]] = $row[$$value];
} else {
if (! is_array($newArr[$row[$$name]])) {
$newArr[$row[$$name]] = array();
}
array_push($newArr[$row[$$name]], $row[$$value]);
}
$x++;
}

Retrieve all parent keys of a given child key in Array

I've been breaking my head over this one but can't seem to find a solution. I need a function that retrieves all parent keys of a given child key. So for example if I have an array like this:
array(
'apples' => array(
'bananas' => array(
'strawberries' => array(
'fruit' => array()
)
)
)
)
I would call the function like 'key_get_parents($key, $array)', and it would return an array with all the parent keys. In this example that would be array('apples', 'bananas', 'strawberries').
$array = array(
'apples' => array(
'bananas' => array(
'strawberries' => array(
'fruit' => array()
)
)
)
);
function key_get_parents($subject, $array)
{
foreach ($array as $key => $value)
{
if (is_array($value))
{
if (in_array($subject, array_keys($value)))
return array($key);
else
{
$chain = key_get_parents($subject, $value);
if (!is_null($chain))
return array_merge(array($key), $chain);
}
}
}
return null;
}
// Prints "Array ( [0] => apples [1] => bananas )"
print_r(key_get_parents('strawberries', $array));

Matching an array value by key in PHP

I have an array of items:
array(
[0] => array(
'item_no' => 1
'item_name' => 'foo
)
[1] => array(
'item_no' => 2
'item_name' => 'bar'
)
) etc. etc.
I am getting another array from a third party source and need to remove items that are not in my first array.
array(
[0] => array(
'item_no' => 1
)
[1] => array(
'item_no' => 100
) # should be removed as not in 1st array
How would I search the first array using each item in the second array like (in pseudo code):
if 'item_no' == x is in 1st array continue else remove it from 2nd array.
// Returns the item_no of an element
function get_item_no($arr) { return $arr['item_no']; }
// Arrays of the form "item_no => position in the array"
$myKeys = array_flip(array_map('get_item_no', $myArray));
$theirKeys = array_flip(array_map('get_item_no', $theirArray));
// the part of $theirKeys that has an item_no that's also in $myKeys
$validKeys = array_key_intersect($theirKeys, $myKeys);
// Array of the form "position in the array => item_no"
$validPos = array_flip($validKeys);
// The part of $theirArray that matches the positions in $validPos
$keptData = array_key_intersect($theirArray, $validPos);
// Reindex the remaining values from 0 to count() - 1
return array_values($keptData);
All of this would be easier if, instead of storing the key in the elements, you stored it as the array key (that is, you'd be using arrays of the form "item_no => item_data") :
// That's all there is to it
return array_key_intersect($theirArray, $myArray);
You can also do:
$my_array =array(
0 => array( 'item_no' => 1,'item_name' => 'foo'),
1 => array( 'item_no' => 2,'item_name' => 'bar')
);
$thrid_party_array = array(
0 => array( 'item_no' => 1),
1 => array( 'item_no' => 100),
);
$temp = array(); // create a temp array to hold just the item_no
foreach($my_array as $key => $val) {
$temp[] = $val['item_no'];
}
// now delete those entries which are not in temp array.
foreach($thrid_party_array as $key => $val) {
if(!in_array($val['item_no'],$temp)) {
unset($thrid_party_array[$key]);
}
}
Working link
If your key is not actually a key of your array but a value, you will probably need to do a linear search:
foreach ($itemsToRemove as $itemToRemove) {
foreach ($availableItems as $key => $availableItem) {
if ($itemToRemove['item_no'] === $availableItem['item_no']) {
unset($availableItems[$key]);
}
}
}
It would certainly be easier if item_no is also the key of the array items like:
$availableItems = array(
123 => array(
'item_no' => 123,
'item_name' => 'foo'
),
456 => array(
'item_no' => 456,
'item_name' => 'bar'
)
);
With this you could use a single foreach and delete the items by their keys:
foreach ($itemsToRemove as $itemToRemove) {
unset($availableItems[$itemToRemove['item_no']]);
}
You could use the following to build an mapping of item_no to your actual array keys:
$map = array();
foreach ($availableItems as $key => $availableItem) {
$map[$availableItems['item_no']] = $key;
}
Then you can use the following to use the mapping to delete the corresponding array item:
foreach ($itemsToRemove as $itemToRemove) {
unset($availableItems[$map[$itemToRemove['item_no']]]);
}

Categories