Taking values from Arrays inside an array - php

Below is the display of my array $arr[0]. Could you please tell me how to take the values of inner array?
Here I need to take only the value for the ID 656 which is 'John'.
Array
(
[0] => xxxxxxxxx
(
[Users] => Array
(
[0] => Array
(
[name] => 656
[value] => John
)
[1] => Array
(
[name] => 657
[value] =>Peter
)
[2] => Array
(
[name] => 658
[value] => Louie
)
[3] => Array
(
[name] => 659
[value] => Jim
)
)
)
Thanks in advance.

try running a:
foreach($arr as $key=>$value){
var_dump($value);
}
And you'll probably be able to work out what to do from there. Hope that helps?
EDIT: if
$arr = array(
0=>array(
'Users'=>array(
0=>array('name'=>656, 'value'=>'John'),
1=>array('name'=>656, 'value'=>'John'),
2=>array('name'=>658, 'value'=>'Louie')
)
)
);
Then you can use:
foreach($arr as $Users){
foreach($Users as $k=>$v){
var_dump($v[0]['value']);
}
}
To get 'John'. Does that help?

If this isn't just a one-off, you could use a recursive array search function. If your data is in $arr, in the format you described:
$arr = array(array("Users"=>array(array("name"=>656,"value"=>"John"),array("name"=>657,"value"=>"Peter"))));
It might look like this:
print in_array_multi("656",$arr);
// ^-- This prints John
print in_array_multi("657",$arr);
// ^-- This prints Peter
function in_array_multi($item, $arr) {
foreach ($arr as $key => $value) {
if ($value==$item){
return $arr['value'];
} else if (is_array($value)){
if($ret = in_array_multi($item, $value))
return $ret;
}
}
return "";
}

for example:
i supose you have 3 arrays to arrive where you wanna ok?
array_1[0].array_2[0].array_3[0]---> here you the information you need.
so you have 2 arrays inside array_1 at position 0.
for(){//to watch the first array all positions
for(){//top watch the second array idem
for(){//to watch the 3 idem...
here at teh position 0 take away the values...
}
}
}
it hope it helps.

Related

How do I skip over first bracket in array with php?

I am needing to echo out the [number], but as you can see each array has a different parent [], how do I by pass the first one and get go to the [number]?
I basically need to skip over first [], and go to the second on that is [number]
Array
(
[e2a4789d22ff47779722b8d8643894cd] => Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 2
[order] => 0
[preferred] => 1
)
)
Array
(
[1603ebeff250437480f5ce046cac36aa] => Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 3
[order] => 0
[preferred] => 1
)
)
Array
(
[215590630122] => Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[order] => 0
[preferred] =>
)
)
Your solution for this is using the foreach-loop. Which gives you then the value of the element as variable you tell PHP to assign to.
foreach($array as $element) {
}
You have to use reset function to get the first element of array.
e.g.
$firstElement = reset($arr);
echo $firstElement['number'];
You can just loop over the elements in the array(s) using foreach.
foreach($data as $ele){
foreach($ele as $id=>$val){
echo $val['number'];
}
}
Just an example
$array = $yourarray;
foreach($array as $k=>$v) {
echo $v['number'] . '<br>';
}
hope this helps...
The first bracket is just a unique key index foreach subsequent set of data. for example you can get the first set by accessing through the key like this
$data['e2a4789d22ff47779722b8d8643894cd']
// will return
Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 2
[order] => 0
[preferred] => 1
)
loop through the array to access the data you want,
// declare your array if you want to save data in array
$numbers = [];
foreach($data $key =>$value){
// echo just the number
echo $value['number'];
// echo the key and number
echo $key.' '.$value;
// or you can build an array
$numbers[$key] = $value['number'];
}
print_r($numbers);
Hope you find this useful, for more info about arrays take a look at this http://php.net/manual/en/language.types.array.php
foreach ($array as $id => $element)
{
// will echo 999-999-9999
echo $element['number'];
}
$array is the whole data structure. We go through as index, that is the $id, which is for example e2a4789d22ff47779722b8d8643894cd and the $element is the element in the $array[$id] so in the $array[e2a4789d22ff47779722b8d8643894cd]
So the $element is the small array in the large array, and it contains data like:
Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 2
[order] => 0
[preferred] => 1
)
So if you need the number attribute, you type $element['number'] and you get it.
If your variable was in an array called $elements then it would look like:
$elements['e2a4789d22ff47779722b8d8643894cd']['number']

Convert complex numerical array to associative array

I have an array data that look like this :
Array (
[0] => Array (
[0] => Name:
[1] => John W.
[2] => Registration ID:
[3] => 36
)
[1] => Array (
[0] =>Age:
[1] => 35
[2] => Height:
[3] => 5'11"
)
[3] => Array (
[0] => Sex:
[1] => M
[2] => Weight:
[3] => 200lbs
)
[4] => Array (
[0] => Address
)
[5] => Array (
[0] => 6824 crestwood dr delphi, IN 46923
))
And I want to convert it to associative array like this :
Array(
['Name']=> John W.
['Registration ID']=> 36
['Age']=> 35
['Height'] => 5'11''
['Sex']=>M
['Weight']=>200lbs
['Address']=>6824 crestwood dr delphi, IN 46923
)
I have no idea at all how to do this, since the supposed to be array column header were also in sequence, so it makes difficult to convert this array.
Any help I appreciate, thx.
Given your origin array is called $origin , you can do it like this:
$merged = array();
foreach($origin as $val) {
$merged = array_merge($merged, $val);
}
$tot = count($merged) - 1;
for ($i=0;$i<$tot;$i+=2) {
$result[$merged[$i]] = $merged[$i+1];
}
var_dump($result); // To test the resulting array
Firstly, I use array_merge() to flatten the $origin array to only one dimension/depth, so we later iterate it (stepping each 2 items per iteration) and assigning each pair of items ($i and $i+1) to the resulting array.
Looks like, for the first 3 children, you can just assign the even value to the previous element as key. Then, assign the fourth one as key for fifth element.
$result = array();
foreach ($array as $key => $value)
{
if ($key < 4) {
$elements = array_values($value);
$result[$elements[0]] = $elements[1];
$result[$elements[2]] = $elements[3];
}
if ($key == 4)
$fifthkey = $value;
if ($key == 5)
$result[$fifthkey] = $value;
}
Also, note that you have to escape your height string quotes.

multiDimensional Array need as

Actual array as below is basically the array of $_POST.
One can understand what is coming from the form. three controls with same name different value. What i need is below this array.
Array
(
[mytext] => Array
(
[0] => aaaa
[1] => bbbb
[2] => ddd
)
[mysel] => Array
(
[0] => one
[1] => two
[2] => two
)
[submit] => Submit
)
I need the array in row format below but be dynamic based of $_POST data.
Array
(
[0] => Array
(
[0] => aaaa
[1] => one
)
[1] => Array
(
[0] => bbbb
[1] => two
)
[2] => Array
(
[0] => dddd
[1] => two
)
)
Try this:
$out = Array();
foreach($_POST['mytext'] as $k=>$v) {
$out[$k] = Array($v,$_POST['mysel'][$k]);
}
var_dump($out);
// Code To Get controls value in row wise
$count=0;
foreach($_POST as $key=>$val){
foreach($_POST[$key] as $val2){
$row[$count][]=$val2;
$count++;
}
$count=0;
}
print_r($row);
Loop through one of the fields, and then pull the corresponding value from the other field.
$result = array();
foreach($_POST['mytext'] as $k=>$v){
$result[] = array($v, $_POST['mysel'][$k]);
}
You can also use array_map to do this:
// PHP 5.3+
$result = array_map(function($a, $b){
return array($a, $b);
}, $_POST['mytext'], $_POST['mysel']);
// PHP <= 5.2
$result = array_map(create_function('$a,$b', 'return array($a,$b);'), $_POST['mytext'], $_POST['mysel']);

combining arrays in php

Lets say I want to combine 2 arrays and the arrays are names $year_into and $likes_dislikes. They share a key called "name". How can I make it so that this one:
$year_info
Array
(
[0] => Array
(
[name] => JOE MONROE
[year] => 1950
[info] => his ghost still haunts us
)
[1] => Array
(
[name] => FUTUREMAN
[year] => 1930
[info] => RIP
)
)
and this one $likes_dislikes
Array
(
[0] => Array
(
[name] => JOE MONROE
[likes] => cornbread
[dislikes] => pain
)
[1] => Array
(
[name] => E. Case
[likes] => chaos
[dislikes] => order
)
[2] => Array
(
[name] => FUTUREMAN
[likes] => mustard
[dislikes] => mayo
)
)
Can be combined into one array $complete that looks like this, where the information from the 2nd array is added to the 1st if the "name" value matches:
Array
(
[0] => Array
(
[name] => JOE MONROE
[year] => 1950
[info] => his ghost still haunts us
[likes] => cornbread
[dislikes] => pain
)
[1] => Array
(
[name] => FUTUREMAN
[year] => 1930
[info] => RIP
[likes] => mustard
[dislikes] => mayo
)
)
I've looked through the already asked questions but don't see anything, maybe I'm using the wrong terminology to describe the problem. I'm stuck on the foreach loop because if I say like this
foreach ($year_info as $y){
$complete[]=array('name'=>$y['name'], 'year'=>$y['year'], 'info'=>$y['info'], 'likes'=$likes_dislikes[0]['likes'],'dislikes'=>$likes_dislikes[0]['dislikes'] )
}
I'll just get the same values for likes/dislikes for all. What is the simplest way to do this?
Here's a crazy one-liner (I guess it technically counts as one line), that should work.
$complete = array_map(function($a) use($likes_dislikes){
foreach($likes_dislikes as $ld){
if($a['name'] === $ld['name']){
return $a + $ld;
break;
}
}
}, $year_info);
This will only work in PHP 5.3+, otherwise you can do it like this:
$complete = array();
foreach($year_info as $a){
foreach($likes_dislikes as $ld){
if($a['name'] === $ld['name']){
$complete[] = $a + $ld;
break;
}
}
}
What I would try to do is loop through both sets of arrays (a nested foreach loop would be a good choice), checking for instances where The name attribute is the same in both arrays. When they are, you can use array_merge() to merge them into a new array. An example would be:
$newArray = array();
foreach ($arr1 as $first) {
foreach ($arr2 as $second) {
if($first["name"] == $second["name"]){
array_push($newArray, array_merge($first, $second));
}
}
}
Assuming you named your arrays $arr1 and $arr2.
The super-lazy, extra-expository approach:
$complete = array();
foreach($year_info as $yr){
$name = $yr['name'];
foreach($likes_dislikes as $ld){
if($ld['name']!=$name){
continue;
}else{
$new_entity = array();
$new_entity['name'] = $name;
$new_entity['year'] = $yr['year'];
$new_entity['info'] = $yr['info'];
$new_entity['likes'] = $ld['likes'];
$new_entity['dislikes'] = $ld['dislikes'];
$complete[] = $new_entity;
break;
}
}
}
Though this will perform poorly with large arrays, it would make more sense to change the data structure if possible. It would be better to have data structures that were simply keyed by name. Do you have control over your input?
just loop over both arrays to create a third one.
$complete = array();
foreach ($year_info as $year) {
foreach ($like_dislikes as $like {
if ($year['name'] == $like['name']) {
$complete[] = array_merge($year, $like);
}
}
}

How can I create multidimensional arrays from a string in PHP?

So My problem is:
I want to create nested array from string as reference.
My String is "res[0]['links'][0]"
So I want to create array $res['0']['links']['0']
I tried:
$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');
when print_r($res)
I see:
<b>Notice</b>: Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>
I need to see:
Array
(
[0] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[class] => 3
)
)
)
[1] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 3
[class] => 9
)
)
)
)
Thanks for any help.
So you have a description of an array structure, and something to fill it with. That's doable with something like:
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
// unoptimized, always uses strings
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );
Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:
array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);
Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.
I have a very stupid way for this, you can try this :-)
Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example
$tmp = '$'.'res[0]['links'][0]'.'= array()';
eval($tmp);
Now you can use your array $res
100% work around and :-)
`
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');
print_r($res);
but read the comments first and learn about arrays first.
In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:
[2] => Array
(
[name] => apple[color]
[value] => red
)
[3] => Array
(
[name] => appleSeeds[27][genome]
[value] => 201
)
[4] => Array
(
[name] => appleSeeds[27][age]
[value] => 2 weeks
)
[5] => Array
(
[name] => apple[age]
[value] => 3 weeks
)
[6] => Array
(
[name] => appleSeeds[29][genome]
[value] => 103
)
[7] => Array
(
[name] => appleSeeds[29][age]
[value] => 2.2 weeks
)
into
Array
(
[apple] => Array
(
[color] => red
[age] => 3 weeks
)
[appleSeeds] => Array
(
[27] => Array
(
[genome] => 201
[age] => 2 weeks
)
[29] => Array
(
[genome] => 103
[age] => 2.2 weeks
)
)
)
This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:
function MergeArrays($Arr1, $Arr2) {
foreach($Arr2 as $key => $Value) {
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else { $Arr1[$key] = $Value; }
}
return $Arr1;
}
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
$sub = array();
array_create($sub, $v['name'], $v['value']);
$result = MergeArrays($result, $sub);
}

Categories