Hello I've multidimensional array that looks like that:
array(13890) {
[0]=>
array(2) {
["Icd"]=>
array(2) {
["id"]=>
int(111)
["nazwa"]=>
string(6) "DŻUMA"
}
["ProjectIcd"]=>
array(0) {
}
}
[1]=>
array(2) {
["Icd"]=>
array(2) {
["id"]=>
int(566)
["nazwa"]=>
string(7) "ŚWINKA"
}
["ProjectIcd"]=>
array(0) {
}
}
An so on.
I want to change it so it looks something like that:
array(13890) {
[0]=> array(2) {
["id"]=>
int(111)
["text"]=>
string(6) "DŻUMA"
}
How is this possible to do?
I want to add, I want to convert the array to json and feed it to select2 js in ajax.
Will that be a problem or not?
Short solution using array_map function:
// $arr is your initial array
$new_arr = array_map(function($a){
return ['id' => $a['Icd']['id'], 'text' => $a['Icd']['nazwa']];
}, $arr);
So you can simple create a new array and add there the values, which you want based on the old array. Then you convert the array to a json string with the php function json_encode():
$array = array("text"=>$old_array[0]["Icd"]["nazwa"]);
echo json_encode($array);
I hope this is something that you want.
$res = [];
$i = 0;
foreach($array as $arr) {
//get keys
if (count($arr) > 0) {
$keys = array_keys($arr);
// loop through the keys and fetch data of those keys
// put in array
foreach($keys as $key) {
if ($arr[$key]) {
$res[$i]['id'] = $arr[$key]['id'];
$res[$i]['text'] = $arr[$key]['nazwa'];
}
$i++;
}
}
}
print_r($res);
// To change array to json
echo json_encode($res);
Related
I have a multidimensional array:
array(3) {
["checkIn"]=> array(0) {}
["code"]=> array(0) {}
[0]=> array(2) {
["checkIn"]=> string(10) "2021-02-02"
["code"]=>string(10) "00Q4K00"
}
}
which I initialize in this way:
$array= array(
'checkIn'=>array(),
'code'=>array()
);
and so I value:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$array[] = array('checkIn'=>$row['checkIn'], 'code'=>$row['code']);
}
I can't figure out how to extract 'code' if '2021-02-02' is present:
if ( in_array('2021-02-02', array_column($array, 'checkIn')) ){
echo code??
}
This question already has answers here:
Filter/Remove rows where column value is found more than once in a multidimensional array
(4 answers)
Closed 9 months ago.
This is the current output I have from an array by doing var_dump($getvals):
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "125mm"
["label"]=>string(5) "125mm"
}
array(2) {
["value"]=>string(5) "125mm"
["label"]=>string(5) "125mm"
}
What I want to achieve is first of all, to ignore the ['label'] tables and then try removing any duplicates (150mm and 125mm). I have tried both array_unique and !inarray() but it won't work. Here is my code:
$getvals = get_sub_field('option_diameter'); // This is my array
$takens = array(); // I create an empty array for later on
foreach ($getvals as $key => $getval){ // Running through the array
if ($key == 'value'){ // Ignoring Label table
if(!in_array($getval, $takens)){ // Check if the current value is already inside $takens array
$takens[] = $getval; // If not, then put it
}
}
}
var_dump($takens); // The output is below
This is what I get from var_dump($takens) :
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "125mm"
}
array(1) {
[0]=>string(5) "125mm"
}
The duplicate values are not removed. Any ideas?
Use a key to remove the duplicate, Demo
$result = [];
foreach($array as $arr){
$result[$arr['value']] = $arr;
}
print_r(array_values($result));
You need to first fetch value by using array_diff_key. Then you need to use array_column, in which passing null as second parameter and unique by value as key to removing duplicates(as keys can not be duplicated). Then to reset indexes array_values
Here is the script,
$takens = array_values(array_column(array_map(function ($a) {
return array_diff_key($a, ['label' => '']);
}, $getvals), null, 'value'));
Demo
Output:-
array(2) {
[0]=>
array(1) {
["value"]=>
string(5) "150mm"
}
[1]=>
array(1) {
["value"]=>
string(5) "125mm"
}
}
You can use array_column
$r = array_values(array_column($a, null, 'label'));
OR
if you want to keep single column
$r = array_values(array_column($a, 'value', 'label'));
print_r($r);
array_values will reorder the keys of the array
Working example :- https://3v4l.org/n8SA1
It look like you forgot a foreach.
Here a test done a few minutes ago :
$aArrayTest = array (
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'125mm',
'label'=>'125mm'
),
array(
'value'=>'125mm',
'label'=>'125mm'
)
);
$aArrayResult = array();
foreach ($aArrayTest as $aArray) { // Running through the array of Arrays
foreach ($aArray as $key => $value){ // Running through each array
if ($key == 'value'){ // Ignoring Label table
if(!in_array($value, $aArrayResult)){ // Check if the current value is already inside $takens array
$aArrayResult[] = $value; // If not, then put it
}
}
}
}
var_dump($aArrayResult);</pre>
I'm using
$data=json_decode($response,true)
the output is
array(3)
{
["instrument"]=> string(7) "EUR_USD" ["granularity"]=> string(1) "D" ["candles"]=> array(10)
{
[0]=> array(7)
{
["time"]=> string(27) "2016-09-26T21:00:00.000000Z" ["openMid"]=> float(1.125495) ["highMid"]=> float(1.1259) ["lowMid"]=> float(1.119125) ["closeMid"]=> float(1.121605) ["volume"]=> int(17059) ["complete"]=> bool(true)
}
[1]=> array(7)
{
["time"]=> string(27) "2016-09-27T21:00:00.000000Z" ["openMid"]=> float(1.1218) ["highMid"]=> float(1.12369) ["lowMid"]=> float(1.118215) ["closeMid"]=> float(1.12171) ["volume"]=> int(17915) ["complete"]=> bool(true)
}
}
}
I want to create two arrays with the values openMid and closeMid for example:
$open=array(1.125495,1.1218)
$close=array(1.121655,1.12171)
I have to develop the foreach code in order to achieve that.
Anyone can help me? Thanks
Check out the solution below:
$open= []; //Declare empty array to hold openMid values
$close= []; //Declare empty array to hold closeMid values
#Loop through $array
foreach ($array as $key => $value) {
#If any of the value is an array
if (is_array($value)) {
$arr= $value; //Store the array
}
}
//Loop through the second array
foreach ($arr as $val) {
//If the value is of index openMid
if ($val->openMid) {
$open[]= $val->openMid; //Push into the $open array holder
}
//If the value is of index closeMid
if ($val->closeMid) {
$close[]= $val->closeMid; //Push into the $close array holder
}
}
Really struggling with this. I have a multidimensional array n levels deep. Each 'array level' has information I need to check (category) and also check if it contains any arrays.
I want to return the category ids of all the arrays which have a category and do not contain an array (i.e. the leaves). I can echo output properly, but I am at a loss as how to return the ids in an array (without referencing)
I have tried RecursiveIteratorIterator::LEAVES_ONLY and RecursiveArrayIterator but I don't think they work in my case? (Maybe I am overlooking something)
$array
array(2) {
["1"]=>
string(5) "stuff"
["2"]=>
array(2) {
["category"]=>
string(1) "0"
["1"]=>
array(3) {
[0]=>
array(3) {
["category"]=>
string(1) "1"
["1"]=>
string(5) "stuff"
["2"]=>
string(5) "stuff"
}
[1]=>
array(5) {
["category"]=>
string(1) "2"
["1"]=>
string(5) "stuff"
["2"]=>
string(5) "stuff"
}
[1]=>
array(5) {
["1"]=>
string(5) "stuff"
["32"]=>
string(5) "stuff"
}
}
}
}
My function
public function recurs($array, $cats = [])
{
$array_cat = '';
$has_array = false;
// Check if an id exists in the array
if (array_key_exists('category', $array)) {
$array_cat = $array['category'];
}
// Check if an array exists within the array
foreach ($array as $key => $value) {
if (is_array($value)) {
$has_array = true;
$this->recurs($value, $cats);
}
}
// If a leaf array
if (!$has_array && is_numeric($array_cat)) {
echo "echoing the category here works fine: " . $array_cat . "\n";
return $array_cat;
}
}
Calling it
$cats_array = $this->recurse($array)
Output echoed
echoing the category here works fine: 1
echoing the category here works fine: 2
How do I return the ids in an array to use in the $cats_array variable?
EDIT: The output should match the echo, so I should get an array containing (1, 2) since they are the only arrays with categories and no arrays within them
array(2){
[0]=>
int(1) "1"
[1]=>
int(1) "2"
}
If I understood you correctly this function will do the job:
function getCategories(array $data)
{
if ($subArrays = array_filter($data, 'is_array')) {
return array_reduce(array_map('getCategories', $subArrays), 'array_merge', array());
};
return array_key_exists('category', $data) ? array($data['category']) : array();
}
If the array contains any sub-arrays they will be returned by array_filter and you will enter the if statement. array_map will apply the function recursively to the sub-arrays and array_reduce will merge the results.
If the array doesn't contain any sub-arrays you will not enter the if statement and the function will return an array with the category if it is present.
Note that you might need to use array_unique to return unique categories.
Also for small performance optimization instead of array_key_exists you can use isset($array[$key]) || array_key_exists($key, $array).
Update
If you want to update your function to make it work you have to recursively collect and merge the sub results. In the following example I introduced a new variable for this:
public function recurs($array, $cats = [])
{
$result = [];
$array_cat = '';
$has_array = false;
// Check if an id exists in the array
if (array_key_exists('category', $array)) {
$array_cat = $array['category'];
}
// Check if an array exists within the array
foreach ($array as $key => $value) {
if (is_array($value)) {
$has_array = true;
$result = array_merge($result, $this->recurs($value, $cats));
}
}
// If a leaf array
if (!$has_array && is_numeric($array_cat)) {
echo "echoing the category here works fine: " . $array_cat . "\n";
return [$array_cat];
}
return $result;
}
I have an array of JSON objects that look like this:
{"id":1,"place":2,"pic_name":"aaa.jpg"}
My PHP file receives a simple array like:
["4","3","1","2","5"]
These numbers correspond to the place value in my JSON object. Now I need to compare the place of each element in the secont array with the value of ID in the JSON object and if the match I have to replace the value of PLACE with the element from the array.
I am having problems doing the comparison. Any guidelines? What I come up with:
foreach($ids as $index=>$id) { //the array
$id = (int) $id;
foreach ($obj as $key=>$value) { //the JSON objects
foreach ($value as $k=>$v){
if ($id != '' && array_search($index, array_keys($ids)) == $value[$k]['id']) {
$value[$k]['place'] = $id;
file_put_contents($file, json_encode($ids));
} else { print "nope";}
} } }
That will be:
$array = [
'{"id":1,"place":2,"pic_name":"aaa.jpg"}',
'{"id":2,"place":5,"pic_name":"aab.jpg"}',
'{"id":3,"place":1,"pic_name":"aba.jpg"}',
'{"id":4,"place":3,"pic_name":"baa.jpg"}',
'{"id":5,"place":4,"pic_name":"abb.jpg"}'
];
$places = ["4","3","1","2","5"];
$array = array_map(function($item)
{
return json_decode($item, 1);
}, $array);
foreach($array as $i=>$jsonData)
{
if(false!==($place=array_search($jsonData['id'], $places)))
{
$array[$i]['place'] = $place+1;
}
}
$array = array_map('json_encode', $array);
//var_dump($array);
-with output like:
array(5) {
[0]=>
string(39) "{"id":1,"place":3,"pic_name":"aaa.jpg"}"
[1]=>
string(39) "{"id":2,"place":4,"pic_name":"aab.jpg"}"
[2]=>
string(39) "{"id":3,"place":2,"pic_name":"aba.jpg"}"
[3]=>
string(39) "{"id":4,"place":1,"pic_name":"baa.jpg"}"
[4]=>
string(39) "{"id":5,"place":5,"pic_name":"abb.jpg"}"
}