php: getting only top value in multidimensional array - php

My nested array looks like:
[Minion] => Array
(
[old_first_name] => "\345\205\265"
[old_last_name] => "\345\274\265"
[old_name] => "\345\205\265\345\274\265"
)
[Evil Minion] => Array
(
[old_first_name] => "\347\251\216"
[old_last_name] => "\345\274\265"
[old_name] => "\345\274\265\347\251\216"
)
[Minion 2] => Array
(
[old_first_name] => "\345\212\233"
[old_last_name] => "\345\274\265"
[old_name] => "\345\274\265\345\212\233"
)
How do I just get Minion, Evil Minion, and Minion 2?
I tried a for loop but it's just looping through the contents of Minion which isn't what I want!

Use the array_keys function:
$keys = array_keys($array);
var_dump($keys);
This works for any array, whether it's one-dimensional or multi-dimensional.

Do this way.. you need to nest furthermore
<?php
$arr= array(
'Minion' => Array
(
'old_first_name' => "\345\205\265",
'old_last_name' => "\345\274\265",
'old_name' => "\345\205\265\345\274\265"
),
'Evil Minion' => Array
(
'old_first_name' => "\347\251\216",
'old_last_name' => "\345\274\265",
'old_name' => "\345\274\265\347\251\216"
),
'Minion 2' => Array
(
'old_first_name' => "\345\212\233",
'old_last_name' => "\345\274\265",
'old_name' => "\345\274\265\345\212\233"
)
);
foreach($arr as $arr1)
{
foreach($arr1 as $k=>$v)
{
echo "$k => $v";
}
}
Demo

You'd be interested in array_keys to just fetch the keys...
$keys = array_keys($arr);
Since this returns an array of the keys, you may further loop through it using a for-each construct.

Related

Getting a value from an associative array.

I'm a beginner and for some reason I'm having trouble with this one. I have the following associative array.
Array
(
[0] => Array
(
[name_type] => UnixName
[name] => charles
)
[1] => Array
(
[name_type] => DNSFQDN
[name] => charles.mydnsdomain.com
)
[2] => Array
(
[name_type] => DNSDomain
[name] => mydnsdomain.com
)
)
The problem is that these arrays are never in the same order and the keys are named the same. I only need the DNSFQDN. When I loop through the array how can I check to see if the DNSFQDN value is there, and then retrieve charles.mydnsdomain.com so I can put it into a varible.
I've tried functions like in_array and array_search but I'm having trouble with these as I'm working strictly with associative arrays.
Any help would be appreciated.
This will be helpful;
$input = array(
array(
'name_type' => 'UnixName',
'name' => 'charles'
),
array(
'name_type' => 'DNSFQDN',
'name' => 'charles.mydnsdomain.com'
),
array(
'name_type' => 'DNSDomain',
'name' => 'mydnsdomain.com'
)
);
$domain = $input[array_search('DNSFQDN', array_column($input, 'name_type'))]['name'];
echo $domain; exit;
// output; charles.mydnsdomain.com
its simple try bellow ..i hope it will help
<?php
$test_array = array(
array('name_type'=>'UnixName','name'=>'charles'),
array('name_type'=>'DNSFQDN','name'=>'charles.mydnsdomain.com'),
array('name_type'=>'DNSDomain','name'=>'mydnsdomain.com'),
);
foreach ($test_array as $key => $value) {
if($value['name_type']=='DNSFQDN'){
echo "Domain Name :";
echo $value['name'];
}
}
?>
You have to iterate array using foreach loop.
<?php
$array_values = array(
array('name_type'=>'UnixName','name'=>'charles'),
array('name_type'=>'DNSFQDN','name'=>'charles.mydnsdomain.com'),
array('name_type'=>'DNSDomain','name'=>'mydnsdomain.com'),
);
foreach ($array_values as $value) {
if($value['name_type']=='DNSFQDN'){
echo "DNSDomain = ".$value['name'];
}
}
?>

Convert and rewrite an array

I need to convert my array but I don't have extended experience to complete this task.
Please help me to find a way to do please?
I have this:
Array(
[0] => Array
(
[BTC] => 0.07634
)
[1] => Array
(
[ETH] => 0.00103
)
[2] => Array
(
[LTC] => 0.006787
)
[3] => Array
(
[XMR] => 0.006351
)
And I need this:
Array(
[BTC] => 0.07634
[ETH] => 0.00103(
[LTC] => 0.006787
[XMR] => 0.006351
[ZEC] => 0.00144
[MD_DT_CAD] => 2017-08-14 02:16:44
)
You have following
$data =array(
array("BTC" => 0.07634),
array("ETH" => 0.00103),
array("LTC" => 0.006787),
array("XMR" => 0.006351)
);
You can achieve your result by following.
<?php
$data =array(
array("BTC" => 0.07634),
array("ETH" => 0.00103),
array("LTC" => 0.006787),
array("XMR" => 0.006351)
);
foreach($data as $value){
foreach ($value as $key => $value1) {
$new_arr[$key] = $value1;
}
}
echo "<pre>";
print_r($new_arr);
?>
Simple use call_user_func_array with array_merge
$array = Array("0" => Array("BTC" => 0.07634),"1" => Array("ETH" => 0.00103),"2" => Array("LTC" => 0.006787),"3" => Array("XMR" => 0.006351));
$new_array = call_user_func_array('array_merge', $array);
print_r($new_array);
<?php $array=array(array("BTC" => 0.07634),array("ETH" => 0.00103),array("LTC" => 0.006787),
array("XMR" => 0.006351));
//echo print_r($array);
$array2 = array_reduce($array, 'array_merge', array());//or call_user_func_array('array_merge', $array);
echo print_r($array2);
?>
Assuming your array is called $array :
$new_array = array_merge(... $array);
Explaination : array_merge() takes an undefined amount of different arrays as parameters, gathers them as entries in a single array by using the splat operator (...) and then merges all these arrays in one before returning it.
Calling that function and passing it a single array and using the splat operator in the calling too makes that single array to be the single array containing the arrays to merge on which the function will work. By doing that, you can have the function to merge sub_arrays of an array you already have without calling additional functions.

How to get the value of an element from a multidimensional JSON string array in PHP

This is the array:
Array
(
[0] => Array
(
[product_details] => {"5f93f983524def3dca464469d2cf9f3e":{"id":"110","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":1400,"name":"Foot Massage","tax":null,"image":"http:\/\/acme.dev\/uploads\/product_image\/product_110_1_thumb.jpg","coupon":"9","book_date_":"2017-04-19","book_date_name_":"wed","start_timeslot_":"09:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"5f93f983524def3dca464469d2cf9f3e","subtotal":1400}}
)
[1] => Array
(
[product_details] => {"2723d092b63885e0d7c260cc007e8b9d":{"id":"109","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":700,"name":"Body Massage","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/product_109_1_thumb.jpg","coupon":"","book_date_":"2017-04-18","book_date_name_":"tue","start_timeslot_":"09:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"2723d092b63885e0d7c260cc007e8b9d","subtotal":700}}
)
[2] => Array
(
[product_details] => {"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id":"108","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":3000,"name":"Alo","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/default.jpg","coupon":"","book_date_":"2017-04-21","book_date_name_":"fri","start_timeslot_":"10:00:00","end_timeslot_":"12:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"a3c65c2974270fd093ee8a9bf8ae7d0b","subtotal":3000}}
)
[3] => Array
(
[product_details] => {"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id":"108","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":3000,"name":"Alo","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/default.jpg","coupon":"","book_date_":"2017-04-12","book_date_name_":"wed","start_timeslot_":"08:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"a3c65c2974270fd093ee8a9bf8ae7d0b","subtotal":3000}}
)
)
What I need is to create a new simple array containing the values from all the "id" elements.
Hope this simple foreach will be helpful for you.
Solution 1: Try this code snippet here
$result=array();
foreach($array as $value)
{
$array= json_decode($value["product_details"],true);
$result[]=$array[key($array)]["id"];
}
print_r($result);
Here we are using array_column to extract product_details then we are using to array_map to iterate over $personalDetails which contain all the JSON's then we are using to key function which will return first key of the array, and through that key we are accessing, its id.
Solution 2: Try this code snippet here
<?php
ini_set('display_errors', 1);
$array = Array
(
0 => Array
(
"product_details" => '{"5f93f983524def3dca464469d2cf9f3e":{"id":"110","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":1400,"name":"Foot Massage","tax":null,"image":"http:\/\/acme.dev\/uploads\/product_image\/product_110_1_thumb.jpg","coupon":"9","book_date_":"2017-04-19","book_date_name_":"wed","start_timeslot_":"09:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"5f93f983524def3dca464469d2cf9f3e","subtotal":1400}}'
),
1 => Array
(
"product_details" => '{"2723d092b63885e0d7c260cc007e8b9d":{"id":"109","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":700,"name":"Body Massage","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/product_109_1_thumb.jpg","coupon":"","book_date_":"2017-04-18","book_date_name_":"tue","start_timeslot_":"09:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"2723d092b63885e0d7c260cc007e8b9d","subtotal":700}}'
),
2 => Array
(
"product_details" => '{"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id":"108","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":3000,"name":"Alo","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/default.jpg","coupon":"","book_date_":"2017-04-21","book_date_name_":"fri","start_timeslot_":"10:00:00","end_timeslot_":"12:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"a3c65c2974270fd093ee8a9bf8ae7d0b","subtotal":3000}}'
),
3 => Array
(
"product_details" => '{"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id":"108","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":3000,"name":"Alo","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/default.jpg","coupon":"","book_date_":"2017-04-12","book_date_name_":"wed","start_timeslot_":"08:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"a3c65c2974270fd093ee8a9bf8ae7d0b","subtotal":3000}}'
)
);
$personalDetails= array_column($array, "product_details");
$result=array_map(function($value){
$array=json_decode($value,true);
return $array[key($array)]["id"];
}, $personalDetails);
print_r($result);
Output:
Array
(
[0] => 110
[1] => 109
[2] => 108
[3] => 108
)
use array_column and json_decode
$new_one = array_column($array,'product_details');
$new_array=[];
foreach($new_one as $key=>$row)
{
foreach(json_decode($row,true) as $key1=>$row1)
{
$new_array[]=$row1['id'];
}
}
print_r($new_array);
you may use array_map & array_value to achieve this,
here is a quick example, and you need to modify it to be fit with your needs :
$ar = [
0 => ['product_details' => '{"5f93f983524def3dca464469d2cf9f3e":{"id": 3}}'],
1 => ['product_details' => '{"2723d092b63885e0d7c260cc007e8b9d":{"id": 8}}'],
2 => ['product_details' => '{"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id": 5}}'],
3 => ['product_details' => '{"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id": 1}}'],
];
$ar = array_map(function ($value) {
return array_values(json_decode($value['product_details'], true))[0]['id'];
}, $ar);
print_r($ar);
live demo : https://3v4l.org/koXee
Try this code, live demo
print_r(array_column(array_map(function($v){return current(json_decode($v));},array_column($array, 'product_details')), 'id'));
You "product_details" seems to be a JSON string. Loop through your array, decode the JSON and store the "id" in a new array.

How to remove null values in multi-dimensional array?

I want to remove null values from this array.
Array(
[0] => Array( [fcmToken] => 123 )
[1] => Array( [fcmToken] => )
[2] => Array( [fcmToken] => 789 )
)
Expected Results
Array(
[0] => Array( [fcmToken] => 123 )
[1] => Array( [fcmToken] => 789 )
)
Here we are using foreach to iterate over values and using $value for non-empty $value["fcmToken"]
$result=array();
foreach($array as $key => $value)
{
if(!empty($value["fcmToken"]))
{
$result[]=$value;
}
}
print_r($result);
Output:
Array
(
[0] => Array
(
[fcmToken] => dfqVhqdqhpk
)
[1] => Array
(
[fcmToken] => dfgdfhqdqhpk
)
)
Use array_filter with a callback:
$r = array_filter($array, function($v) { return !empty($v['fcmToken']); });
For checking exactly null:
$r = array_filter($array, function($v) { return !is_null($v['fcmToken']); });
The best and easy single line solution for filter multidimensional array like below.
$aryMain = array_filter(array_map('array_filter', $aryMain));
I hope this solution is work for you. for more detail please visit below link.
PHP: remove empty array strings in multidimensional array
Danger! Do not trust empty() when dealing with numbers (or number-ish) values that could be zero!!! The same is true with using array_filter without a specific filtering parameter (as several answers on this page are using).
Look at how you can get the wrong output:
Bad Method:
$array = array(
array("fcmToken" => '0'),
array("fcmToken" => 123),
array("fcmToken" => ''),
array("fcmToken" => 789),
array("fcmToken" => 0)
);
$result=array(); // note, this line is unnecessary
foreach($array as $key => $value){ // note, $key is unnecessary
if(!empty($value["fcmToken"])){ // this is not a reliable method
$result[]=$value;
}
}
var_export($result);
Output:
array (
0 =>
array (
'fcmToken' => 123,
),
1 =>
array (
'fcmToken' => 789,
),
)
The zeros got swallowed up!
This is how it should be done:
Instead, you should use strlen() to check the values:
Method #1: foreach()
foreach($array as $sub){
if(strlen($sub["fcmToken"])){
$result[]=$sub;
}
}
var_export($result);
Method #2: array_filter() w/ anonymous function and array_values() for consistency
var_export(array_values(array_filter($array,function($a){return strlen($a['fcmToken']);})));
Output for either method:
array (
0 =>
array (
'fcmToken' => '0',
),
1 =>
array (
'fcmToken' => 123,
),
2 =>
array (
'fcmToken' => 789,
),
3 =>
array (
'fcmToken' => 0,
),
)
Demonstration of bad method and two good methods.
You need to do it using array_map, array_filter and array_values. Check below code :
$entry = array(
array("fcmToken" => 'dfqVhqdqhpk'),
array("fcmToken" => ''),
array("fcmToken" => 'dfgdfhqdqhpk'),
);
echo "<pre>";
$entry = array_values(array_filter(array_map('array_filter', $entry)));
print_r($entry);
Use this recursive function which iterates over any subarray and remove all elements with a null-value.
function removeNullValues ($array) {
foreach ($array as $key => $entry) {
if (is_array($entry)) {
$array[$key] = removeNullValues($entry);
if ($array[$key] === []) {
unset($array[$key]);
}
} else {
if ($entry === null) {
unset($array[$key]);
}
}
}
return $array;
}
Try using array_map() to apply the filter to every array in the array.

PHP dealing with arrays

Array
(
[0] => Array
(
[uid] => 43543534
)
)
I'm trying to get output as [0] => [43543534]
I tried foreach() but I'm getting string as output
Update How do i find max value now in this?
Why don't you have only 1 dimensional array array('0' => 43543534), if you have only 'uid' in the second one
foreach ($yourArray as $key => $val) {
echo '['.$key.'] => ['.$val['uid'].']<br />';
}
$var = array( '0' => array ( 'uid' => '43543534' ) );
foreach($var as $arr):
echo $arr['uid'];
endforeach;
Your question is very unclear, but here are two ways to accomplish that using the original array:
$array = array( '0' => array ( 'uid' => '43543534' ) );
$result[0] = $array[0]['uid];
or with foreach
$array = array( '0' => array ( 'uid' => '43543534' ) );
foreach($array as $a){
$result[] = $a['uid'];
}

Categories