How to get all keys out of associative array in php - php

I have an associative array in php. When I am doing a die on it, then I am getting proper values as follows:
array(1) { [0]=> array(1) { [123]=> string(5) "Hello" }}
But when I am trying extract out keys of this array into an new array, then I am not able to get keys out:
$uniqueIds = array_keys($myAssociativeArray);
die(var_dump($uniqueIds));
int(0) array(1) { [0]=> int(0) }
Can any one tell me what I am doing wrong here? I want to get all the keys out of my associative array. And for this, I am referring to thread: php: how to get associative array key from numeric index?

$uniqueIds = array_keys($myAssociativeArray[0]);

<?php
function multiarray_keys($ar) {
foreach($ar as $k => $v) {
$keys[] = $k;
if (is_array($ar[$k]))
$keys = array_merge($keys, multiarray_keys($ar[$k]));
}
return $keys;
}
$result = multiarray_keys($myAssociativeArray);
var_dump($result);
?>

The following recursively gets all the keys in an associative array
function getArrayKeysFlat($array) {
if(!isset($keys) || !is_array($keys)) {
$keys = array();
}
foreach($array as $key => $value) {
$keys[] = $key;
if(is_array($value)) {
$keys = array_merge($keys,getArrayKeysFlat($value));
}
}
return $keys;
}

Related

Retrieve indexes of value in array

Is it possible to search an array for a given value and return all the indexes at which the value was found? So for this array:
["Red","Green","Red","Blue"]
I need
[0,2]
with regard to a search for "Red". Searching for "Yellow" in this case would return an empty array.
You can use like this:
$array = ["Red","Green","Red","Blue"];
$output = array_keys($array, "Red");
The $output will be [0,2]
I think this should work:
$input = ["Red","Green","Red","Blue"];
$x = "Red";
$keys = array_keys(array_filter($input, function ($v) use ($x) { return $v === $x;}));
You can iterate the array with foreach:
foreach($input_arr as $key => $value){
if($value == 'Red'){
needed_key_arr[] = $key;
}
}
Also, if you can have an array of values you what to search use:
$lookup_arr = ['Red', 'Green'];
foreach($input_arr as $key => $value){
if(in_array($value, $lookup_arr)){
needed_key_arr[] = $key;
}
}
$arr = ["Red","Green","Red","Blue"];
$valueToSearchFor = ["Red"];
$keys = array_keys(array_filter($arr, function ($val1) use ($valueToSearchFor) { // filter the first array
return array_filter($valueToSearchFor, function ($val) use ($val1) { // use the first array's value
return $val == $val1; // compare them and then return them
});
}));
var_dump($keys) // array(2) { [0]=> int(0) [1]=> int(2) }
First we filter the array then take the values from the first filter to another filter then we match the arrays and we return them. This works for multiple values too.
$arr = ["Red","Green","Red","Blue"];
$valueToSearchFor = ["Red", "Blue"];
$keys = array_keys(array_filter($arr, function ($val1) use ($valueToSearchFor) {
return array_filter($valueToSearchFor, function ($val) use ($val1) {
return $val == $val1;
});
}));
var_dump($keys) // array(3) { [0]=> int(0) [1]=> int(2) [2]=> int(3) }

Php array value to keys

Hi let's say I have this array
array(2) {
[0]=>
string(9) "name|a-z+"
[1]=>
string(7) "id|0-9+"
}
Now I want a new array (or the same if possible) to be like this:
array(2) {
[name]=>
string(4) "a-z+"
[id]=>
string(4) "0-9+"
}
I think the solution implies explode and array_combine, but I am not good enough, can someone help me?
Thanks in advance.
function convert_my_array($arr){
$out = array();
foreach($arr as $obj){
$data = explode("|", $obj);
$out[$data[0]] = $data[1];
}
return $out;
}
Using the original array called $array here, loop through it set the values to what you want.
$newarray = array();
foreach ($array as $key=>$val) {
list($one, $two) = explode('|', $val);
$newarray[$one] = $two;
}

php loop through array

I am trying to get certain values from an array but got stuck. Here is how the array looks:
array(2) {
[0]=>
array(2) {
["attribute_code"]=>
string(12) "manufacturer"
["attribute_value"]=>
string(3) "205"
}
[1]=>
array(2) {
["attribute_code"]=>
string(10) "silhouette"
["attribute_value"]=>
array(1) {
[0]=>
string(3) "169"
}
}
}
So from it I would like to have attribute_values, and insert it into a new array, so in this example I need 205 and 169. But the problem is that attribute_value can be array or string. This is what I have right now but it only gets me the first value - 205.
foreach ($array as $k => $v) {
$vMine[] = $v['attribute_value'];
}
What I am missing here?
Thank you!
If sometimes, attribute_value can be an array, and inside it the values, you can just check inside the loop (Provided this is the max level) using is_array() function. Example:
$vMine = array();
foreach ($array as $k => $v) {
if(is_array($v['attribute_value'])) { // check if its an array
// if yes merge their contents
$vMine = array_merge($vMine, $v['attribute_value']);
} else {
$vMine[] = $v['attribute_value']; // if just a string, then just push it
}
}
I suggest you to use array_map instead of for loop. You can try something like this..
$vMine = array_map(function($v) {
return is_array($v['attribute_value']) ? current($v['attribute_value']) : $v['attribute_value'];
}, $arr);
print '<pre>';
print_r($vMine);
Try the shorthand version:
foreach ($array as $k => $v) {
$vMine[] = is_array($v['attribute_value']) ? current($v['attribute_value']):$v['attribute_value'];
}
or the longer easier to understand version, both is the same:
foreach ($array as $k => $v) {
if(is_array($v['attribute_value'])) {
$vMine[] = current($v['attribute_value']);
} else {
$vMine[] = $v['attribute_value'];
}
}

How to change value of one element to key in array?

How can I make value of one element into key in the same array
from this
[0]=>
array(2) {
["name"]=>
string(7) "segment"
["value"]=>
string(9) "Name Test"
}
to this
["segment"]=> "Name Test"
Try and run each item through a function or foreach loop assigning it as you want.
$res = array();
foreach($data as $item)
{
$res[$item['name']] = $item['value'];
}
Or through a function such as array_walk
$res = array();
array_walk($data, function($item, $key) use (&$res) {
$res[$item['name']] = $item['value'];
});
Simplifying (if you have one row indexed as '0'):
$array = array('0' => array('name'=>'segment'
'value'=>'Name Test'));
$new_array = array();
$new_array[$array[0]['name']] = $array[0]['value'];
print_r($new_array);

Changes to array of JSON objects based on other array

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"}"
}

Categories